Home > DeveloperSection > Forums > NSAutorelease pool how it works
Tarun Kumar

Total Post:210

Points:1614
Posted on    August-10-2015 11:20 PM

 iPhone iPhone  Ios  Objective C 
Ratings:


 1 Reply(s)
 456  View(s)
Rate this:

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

}


Nigel Bunyan
Nigel Bunyan

Total Post:20

Points:140
Posted on    August-11-2015 11:26 PM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick