2011年5月15日 星期日

Fundation Framework-記憶體管理 CH17-6 Autorelease

//

// main.m

// CH17-6 Autorelease

//

// Created by jason on 2011/5/15.

// Copyright 2011 __MyCompanyName__. All rights reserved.

//


//#import


#import

#import


@interface Foo : NSObject

{

int x;

}

@end


@implementation Foo

@end


int main(int argc, char *argv[])

{

NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];

Foo *myFoo = [[Foo alloc] init];

NSLog(@"myFoo retain count = %x", [myFoo retainCount]); // Ref. count = 1; 剛建立都是 1

[pool drain];

NSLog(@"after pool drain = %x", [myFoo retainCount]); // Ref. count = 1; [pool drain ] 還是1 ! 因為 它還沒加入 autorelease

pool= [[ NSAutoreleasePool alloc] init]; // 重建 pool

[myFoo autorelease];

NSLog(@"after autorelease = %x", [myFoo retainCount]); // 加入autorelease 不會變動 Ref. count =1

[myFoo retain]; // retain 一次

NSLog(@"after retain count = %x", [myFoo retainCount]); // Ref. count =2

[pool drain]; // 再次 pool drain

NSLog(@"after second pool drain = %x", [myFoo retainCount]); // Ref. Count = 1 ,這次透過 autorelease 有把 Ref. count 減一

[myFoo release]; // 再次釋放 myFoo

return 0;

//return NSApplicationMain(argc, (const char **) argv);

}

沒有留言: