objective-c 内存管理之 "autorelease"的疑问 ---何时release对象(转)

来源:互联网 发布:卡易信5.0源码 编辑:程序博客网 时间:2024/05/22 11:43

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,它会在这个方法结束后被立即释放.


The built in auto-release pool is usually popped at the end of an event loop, but this may not be desired when you have a loop that is allocating a lot of memory in each iteration. In that case, you can create an auto-release pool in the loop. Auto-release pools can be nested so the objects allocated in the inner pool will be released when that pool is popped. In the example below, objects will be released at the end of each iteration.

for (int i = 0; i < 10; ++i){    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];    NSString* str = [NSString stringWithString:@"hello world"];    [self ProcessMessage: str];    [pool drain];}

Note: At the time of writing, the iPhone doesn't support garbage collecting, so drain will work the same as releasedrain is often used in cases where you want to port the program to OSX, or if garbage collecting is added to the iPhone later. drain provides a hit to the garbage collector that memory is being released.


原创粉丝点击