Need clarification for NSAutoreleasePool

2019-05-11 20:31发布

问题:

Whenever we are calling autorelease method, its object is going to NSAutoreleasePool. When the pool is drained, it is sending release to all the objects in the pool.

My question is;
In the main function there is one NSAutoreleasePool. I want to know that; when we call the autorelease method, where it is sending the object ? I mean; it is sending the object to NSAutoreleasePool which is in main function (or) somewhere ?

Thanks in advance.

回答1:

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"