简体   繁体   中英

When is an object with 'autorelease' released?

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM