views:

523

answers:

3

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, i.e. the reference count (or retain count) keeps the same when I add an object to an autorelease pool?

A: 

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]]);
oxigen
+2  A: 

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.

Martin Gordon
+6  A: 

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.

duncanwilcox