NSAUTORELEASE POOL HOW IT WORKS

Tarun Kumar

Total Post:214

Points:1642
Posted by  Tarun Kumar
 851  View(s)
Ratings:
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];

}
  1. Nigel Bunyan

    Post:20

    Points:140
    Re: NSAutorelease pool how it works

    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

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!