Need clarification for NSAutoreleasePool

落花浮王杯 提交于 2019-12-06 01:50:00
DarkDust

There is actually a stack of autorelease pools. Whenever you do [[NSAutoreleasePool alloc] init] that newly created pool is automatically put on top of the autorelease pool stack. You can create your own pools whenever you need it.

To be more precise: there is a stack of autorelease pools on each thread. So whenever you create a thread (for example with [foo performSelectorInBackground:@selector(bar) withObject:baz]) the very first thing you need to do is create a pool or else your objects leak (this creates the infamous messages like "NSAutoreleaseNoPool(): Object 0xd819d0 of class NSCFString autoreleased with no pool in place - just leaking" and is a very frequently asked question here on SO).

When you call autorelease, the object is registered with the top-most autorelease pool of the current thread (that is: the one that was created last on that thread). The main run loop has its own autorelease pool that is emptied on each run loop iteration (AFAIK). The pool from main.m is there to catch any objects that for example might be generated internally by Cocoa Touch before it gets to create the run loop autorelease pool.

Edit: For more behind-the-scenes information, see Mike Ash's "Let's Build NSAutoreleasePool"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!