views:

50

answers:

1

What happen when we are writing [Obj autorelease] ?

For example:

 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];<br>
 NSMutableString *str = [[[NSMutableString alloc]initWithString:@""] autorelease];<br>
 NSLog(str);<br>
 [str appendString:@" I"];<br>
 NSLog(str);<br>
 [str appendString:@" like"];<br>
 NSLog(str);<br>
 [str appendString:@" programming"];<br>
 NSLog(str);<br>
 [pool drain];<br>
 NSLog(@"%@",str); //invalid

I am confused because i read that "You can add an object to the current autorelease pool for later release by sending it an autorelease message", so when i write

 NSMutableString *str = [[[NSMutableString alloc]initWithString:@"my"] autorelease];

1) After executing above statement, Is str now added to autorelease pool?

2) If str is added to autorelease pool, then if we refer str after that (before releasing/draining pool), like...

 [str appendString:@" I"];
 NSLog(str);
 [str appendString:@" like"];
 NSLog(str);
 [str appendString:@" programming"];
 NSLog(str);

then reference of str will be available from autorelease pool(because str is now added to autorelease pool) or from initial memory location of str....??

Confusing...!! Can any one give me clear idea about this!

+2  A: 

1) Yes, whenever you send an object an -autorelease message, it is added to the autorelease pool.

2) After executing the following line of code...

NSMutableString *str = [[[NSMutableString alloc]initWithString:@"my"] autorelease];

(which, by the way, could be rewritten like this):

NSMutableString *str = [NSMutableString string]; 

...there are two references to the new string; one in the autorelease pool, and the second in your local variable str. In other words, each contains the address of your string object. So the object isn't really 'in' the pool, anymore than it's 'in' the variable.

When you send a -release message to the pool, it sends -release messages to the objects it currently references. Note that a single object can be sent multiple -autorelease messages in a given cycle, in which case the pool would send a corresponding number of -release messages to the object.

If you're finding this stuff confusing, a great way to get more insight is to read Apple's Memory Management Guide.

jlehr
Worth expanding upon: `str` does not contain the object, nor does the pool. The initial chain of `alloc`, `init`, and `autorelease` messages returns the pointer to the object, and it's that pointer that you put into the variable. When you send the `autorelease` message to the object, the `autorelease` method puts the same pointer into the pool as well. The pointer is in both places; the object is always only in one place, to which both pointers point.
Peter Hosey