How does the NSAutoreleasePool autorelease pool work?
Solution 1:
Yes, your second code snippit is perfectly valid.
Every time -autorelease is sent to an object, it is added to the inner-most autorelease pool. When the pool is drained, it simply sends -release to all the objects in the pool.
Autorelease pools are simply a convenience that allows you to defer sending -release until "later". That "later" can happen in several places, but the most common in Cocoa GUI apps is at the end of the current run loop cycle.
Solution 2:
NSAutoreleasePool: drain vs. release
Since the function of drain
and release
seem to be causing confusion, it may be worth clarifying here (although this is covered in the documentation...).
Strictly speaking, from the big picture perspective drain
is not equivalent to release
:
In a reference-counted environment, drain
does perform the same operations as release
, so the two are in that sense equivalent. To emphasise, this means you do not leak a pool if you use drain
rather than release
.
In a garbage-collected environment, release
is a no-op. Thus it has no effect. drain
, on the other hand, contains a hint to the collector that it should "collect if needed". Thus in a garbage-collected environment, using drain
helps the system balance collection sweeps.
Solution 3:
As already pointed out, your second code snippet is correct.
I would like to suggest a more succinct way of using the autorelease pool that works on all environments (ref counting, GC, ARC) and also avoids the drain/release confusion:
int main(void) {
@autoreleasepool {
NSString *string;
string = [[[NSString alloc] init] autorelease];
/* use the string */
}
}
In the example above please note the @autoreleasepool block. This is documented here.
Solution 4:
No, you're wrong. The documentation states clearly that under non-GC, -drain is equivalent to -release, meaning the NSAutoreleasePool will not be leaked.