How does the NSAutoreleasePool autorelease pool work?
As I understand it, anything created with an alloc , new , or copy needs to be manually released. For example:
int main(void) {
NSString *string;
string = [[NSString alloc] init];
/* use the string */
[string release];
}
My question, though, is wouldn't this be just as valid?:
int main(void) {
NSAutoreleasePool *pool;
pool = [[NSAutoreleasePool alloc] init];
NSString *string;
string = [[[NSString alloc] init] autorelease];
/* use the string */
[pool drain];
}
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.
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.
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.
链接地址: http://www.djcxy.com/p/72752.html上一篇: 为什么使用Autorelease池?