Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is an object with 'autorelease' released?

Tags:

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

like image 344
Mark Avatar asked Jul 18 '09 02:07

Mark


People also ask

How is Autorelease pool managed?

An autorelease pool stores objects that are sent a release message when the pool itself is drained. If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks.

What is Autoreleasepool Swift?

Memory management in swift is handled with ARC (= automatic reference counting). This means that active references to objects are counted and objects are released when they aren't referenced anymore.


1 Answers

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.

like image 166
Jonathon Avatar answered Sep 22 '22 00:09

Jonathon