十二、AutoreleasePool使Objective-C成为内存管理半自动化语言。
如果仅仅是上面这些,很简单,对吧。但往往很多人都会迷糊在自动内存管理这块上,感觉像是有魔法,但其实原理也很简单~
先看看最经典的程序入口程序:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
我们先把pool看成一个普通对象~很简单,先是alloc,pool的retainCount为1。第三句release,retainCount为0,自动调用它的dealloc方法。它和任何其它普通对象没 任何区别。
魔法在哪里?
在声明pool后,release它之前的这段代码,所有段里的代码(先假设中间没有声明其它的AutoreleasePool实例),凡是调用了autorelase方法的实例,都会把它的retainCount加1,并在此pool实例中添1次此实例要回收的记录以做备案。当此pool实例dealloc时,首先会检查之前备案的所有实例,所有记录在案的实例都会依次调用它的release方法。
代码:
NSObject *o = [[NSObject alloc] init];
[o autorelease]; //在pool实例dealloc时,release一次此实例,重要的是并不是在此行去release
NSLog(@"o retainCount:%d",[o retainCount]); //此时还可以看到我们的o实例还是可用的,并且retainCount为1
[pool release]; //pool 的 retainCount为0,自动调用其dealloc方法,我们之前备案的小o也将在这里release一次(因为咱们之前仅仅autorelease一次)
真对同一个实例,同一个Pool是可以多次注册备案(autorelease)的。在一些很少的情况化可能会出现这种需求:
代码:
NSObject *o = [[NSObject alloc] init];
[o retain];
[o autorelease];
[o autorelease];
[pool release];
我们调用了两次A类(retainCount加1的方法),使其retainCount为2,而接下来的两次autorelease方法调用,使其在pool中注册备案了两次。这里的pool将会在回收时调用此实例的两次release方法。使其retainCount降为0,完成回收内存的操作,其实这也是完全按照内存管理规则办事的好处~