How does the NSAutoreleasePool autorelease pool work?

James Sumners picture James Sumners · Sep 15, 2008 · Viewed 86.5k times · Source

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];
}

Answer

kperryua picture kperryua · Sep 15, 2008

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.