NSAutorelease pool how it works

Total Post:214


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

  1. 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.

      Modified On Apr-10-2018 02:08:17 AM


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.