views:

18

answers:

2

Hi,

My question is when a object is actually added to autorelease pool? When a Autorelease pool is created and objects are declared within the scope, are they added in autorelease pool or they are added in pool when specified as autoreleased.

int main(void) { 
    NSAutoreleasePool *pool; 
    pool = [[NSAutoreleasePool alloc] init]; 
    NSString *string; 
    NSArray * array;
    string = [[[NSString alloc] init] autorelease]; 
    array = [[NSArray alloc] init];
    /* use the string */ 
    [pool drain]; 
} 

In this case is only string is added to pool or even array is added to pool?

A: 

Objects are added to autorelease pools (yes, pools, there's a stack of them per thread) when -autorelease is called on them, and only then. However, in methods that don't contain the words 'new', 'alloc', or 'copy' (more or less, I might be forgetting one or two), the returned value is usually autoreleased for you, before it is returned. You should really read the memory management guide in full (it's not that painful).

Jared P
Thanks for the reply Jared..I also have another doubt is when i create nested pools can i use the object in nested pool as autorelease, where the object is created in the parent pool.
Cathy
@Cathy: yes you can, but this will likely confuse memory management -- as the docs say, don't release something you didn't create or retain. Basically I can't think of a situation where you would do this cleanly, although it's absolutely technically fine, so long as you don't over-release it (by autoreleasing it twice)
Jared P
A: 

Objects are added to the autorelease pool only when they are sent the autorelease method.

Autorelease pools stack and the object is added only to the topmost pool (most recently created) in the stack at the time the object is sent autorelease.

However, autorelease pools themselves are effectively in the next pool down the stack. Thus if you drain the oldest pool, all the pools created since then will also be drained. This is important in the context of throwing exceptions. It makes it possible to throw an exception through a stack frame with an autorelease pool in it without leaking the pool or the objects in it.

JeremyP