Advertise with us

NSAutorelease pool how it works

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

}
Last updated:8/11/2015 11:26:56 PM

1 Answers

Nigel Bunyan
Nigel Bunyan

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.

Answer