When does autorelease actually cause a release in Cocoa Touch?

六眼飞鱼酱① 提交于 2019-11-30 06:59:38

The autorelease pool is typically released after each iteration of the run loop. Roughly, every Cocoa and Cocoa Touch application is structured like this:

Get the next message out of the queue
Create an autorelease pool
Dispatch the message (this is where your application does its work)
Drain the autorelease pool

What you describe is the expected behavior. If you want to keep an object around any longer than that, you'll need to explicitly retain it.

Using autorelease is a way of saying, "Object, I don't want you anymore, but I'm going to pass you to somebody else who might want you, so don't vanish just yet." So the object will stick around long enough for you to return it from a method or give it to another object. When some code wants to keep the object around, it must claim ownership by retaining it.

See the memory management guidelines for everything you need to know to use autorelease correctly.

thierryb

Here is an examle provided in the Apple Memory Management document:

– (id)findMatchingObject:(id)anObject 
{ 
    id match = nil; 
    while (match == nil) { 
        NSAutoreleasePool *subPool = [[NSAutoreleasePool alloc] init]; 
        /* Do a search that creates a lot of temporary objects. */ 
        match = [self expensiveSearchForObject:anObject]; 
        if (match != nil) { 
            [match retain]; /* Keep match around. */ 
        } 
        [subPool release]; 
    } 
    return [match autorelease];   /* Let match go and return it. */ 
}

Yes, that's the best approach. Autorelease is really only intended for interactions in code that you know. Once you're storing an object, you should either know that the object that holds a reference will not die/go out of scope until you're also done with the object, or you need to retain the object.

It is only guaranteed that autoreleased objects will be released after the end of your method. After all, the method that called your method could have created its own pool and release it right after your method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!