Objective-c – When is an object with ‘autorelease’ released

objective c

I'm developing for iPhone, objective-c. When we use autorelease, when does the object actually get released – when the main autorelease pool gets released (ie. the application terminates?), or as soon as the local function ends? For example, I want to do something like this:

- (void) test
{
    MyObj* p = [[[MyObj alloc] init] autorelease];
    ...

    // is p 'released' here?
}

So is 'p' released as soon as the function exits, or when the autorelease pool of this thread is released? I thought it was when the local function exits, but I just created my own thread and needed to setup an autorelease pool which is giving me second thoughts on when this actually happens..

Thanks

Best Answer

An autoreleases object is released the same time the autorelease pool is. So for your thread it will be released when you release the pool. In the main thread, if you don't create your own, I believe the autorelease pool is drained every time through the run loop -- but I haven't looked at in a while.

Related Topic