tags:

views:

126

answers:

2

Hi,

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

+6  A: 

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.

Argothian
Here's the link to the page on autorelease pools: http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html
Argothian
+1  A: 

As Argothian says, it is released when the autorelease pool is released, which happens every time through the run loop in a normal Cocoa application, not at application termination (unless of course you don't have a run loop, in which case you have to create the autorelease pool, and release it yourself). Autorelease pools don't know about each individual function call, and so could not release things at the end of a function call.

Logan Capaldo