How are objects in an autorelease pool referenced?

I am wondering if the autorelease pool holds strong or weak references to the objects it holds. I would guess they are weak. When I add an object to an autorelease pool, it's just not immediately released but will be released when the pool is drained, right? So the references should be weak, ie the reference count (or retain count) keeps the same when I add an object to an autorelease pool?


Talking of strong versus weak references makes sense in the context of a garbage collected memory management environment (where weak pointers are automatically released and cleared even if referenced). With GC enabled, all retain/release/autorelease calls are essentially do nothing operations (though the NSAutoreleasePool -drain method triggers garbage collection).

Now since you've tagged this question as iPhone related, and there's no garbage collection on iPhone, I'm assuming you're referring to regular reference counting, by strong you mean increasing the retain count of the referenced object, and by weak you mean just storing the pointer value.

The autorelease method essentially moves ownership of an object from the calling code to the current autorelease pool, you can think of the calling code calling release and the pool calling retain.

So the reference is effectively strong, but your code loses ownership and release responsibility. Object release will be called when the autorelease pool is released/drained.


The whole point of the autorelease pool is that it is a deferred release. For example, you can call autorelease on a local object you will be returning in a method so that it gets released even though you lose the reference to the object when the method returns.


Yes. retain count keeps the same, and yo can can check, that it is so:

id obj = [[NSObject alloc]init];
    NSLog([NSString stringWithFormat: @"%d", [obj retainCount]]);
    [obj autorelease];
    NSLog([NSString stringWithFormat: @"%d", [obj retainCount]]);
链接地址: http://www.djcxy.com/p/53268.html

上一篇: 什么时候自动释放对象被释放?

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