When does autorelease actually cause a release in Cocoa Touch?

I understand you need to be careful with autorelease on iOS. I have a method that is returning an object it alloc s which is needed by the caller, so in this situation -- as I understand it -- I need to send autorelease to the object in the callee before it returns.

This is fine, but once control returns to the phone (ie after my button click has been processed) it seems that the autorelease pool is released. I suspect this is how it is supposed to be, but I am wondering what is the best practice for this situation.

I have resorted to sending a retain message from the caller so that the object is not released and then explicitly releasing it in dealloc .

Is this the best approach?


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 retain ing it.

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


这是Apple Memory Management文档中提供的一个例子:

– (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. */ 
}
链接地址: http://www.djcxy.com/p/53266.html

上一篇: 如何引用autorelease池中的对象?

下一篇: autorelease什么时候真的会在Cocoa Touch中导致发布?