objective-c 内存储器管理之 "autorelease"的一个疑问

objective-c 内存管理之 "autorelease"的一个疑问

autorelease的用法我了解,但是我一直有一个疑问:

 

比如说项目中我没有加其他的 NSAutoreleasePool ,也就是说项目中只有 主线程中的那个 NSAutoreleasePool.

我现在有(就拿NSString举例了)

 

- (IBAction)clickBtn:(id)sender

{

     NSString *string = [[NSString alloc] initWithString:@"1234567890"];

     [string autorelease];

}

 

我一直不明白的是,这个string什么时候被释放呢?

刚开始看obj-c的介绍书籍时,书上说: 每一个autorelase会将该变量注册到一个自动线程池,当线程池销毁时,会给该对象发一个relase消息,并将其销毁."

对于这个说法我很是疑惑,要真是这样,比如说我只有一个主线程中的 NSAutoreleasePool,我程序中那些autorelease的对象就只能等到主线程中的NSAutoreleasePool销毁时被销毁. 那也就是说,要等到程序退出了,这些对象才会被销毁.

很显然这个说法是有问题的.

 

这两天空闲的时间比较多,,终于把这个问题给弄明白了.

首先,关于autorelease,我找到了比较权威的说法:

 

---------------

Objects set to auto-release mean that they do not need to be explicitly released because they will be released when an auto-release pool is popped. The iPhone has an auto-release pool that runs on the main thread which usually releases objects at the end of an event loop. When you create your own threads, you must create your own auto-release pool.

---------------

from : http://www.codeproject.com/KB/iPhone/avoidiphoneleaks.aspx?display=Mobile

(在Eric Sadun的<< the iphone developer's cookbook>> 2rd 也有这样的介绍)

 

也就是说,一个autorelease的对象在事件结束后会被主线程的自动释放池释放掉.

比如上面 clickBtn:中的string,它会在这个方法结束后被立即释放.

 

至此,,这个问题就算是回答完毕了,最后补充三点:

1.程序中所有的NSAutoreleasePool对象都会被加到一个"栈"中,当你将一个对象定义为autorelease时,"栈"中最上面的NSAutoreleasePool对象负责管理的该对象的销毁.

2.碰到一些不明白的问题,很简单写个小程序,不费什么功夫.

3.刚开始学习一个新的技术,不能只看一本书,书毕竟是人写的,难免有疏漏或误导之处.