views:

179

answers:

3

In the docs there is an addObject: method of NSAutoreleasePool.

I thought about this:

NSString *myString = [[NSString alloc] initWithCString:"Does this work?"]; [thePool addObject:myString]; [anotherPool addObject:myString];

Is that possible? I always read that I can only add objects to the topmost one on the autorelease pool stack.

+2  A: 

What you are doing is possible, but may cause an exception at run time because myString will be sent a -release message after deallocation (assuming the last remaining reference is by the first pool). In general, as the -[NSAutoreleasePool addObject:] documentation states, you should not add an object to an autorelease pool manually but rather by calling -autorelease on that object. This will put the object in the active autorelease pool for the current thread (each thread has its own autorelease pool).

Barry Wark
+6  A: 

Yes, you can. But you never should. There is categorically no reason to do this.

Chuck
A: 

I am a little bit confused now because of this from Apple:

When an object is autoreleased—that is, when an object is sent an autorelease message or when it is passed as the argument to the addObject: class method—it is always put in the autorelease pool at the top of the stack.

On the other side, they don't mention it in the NSAutoreleasePool Class Reference. So I guess even when I cal addObject: on a specific one, then it will go onto the one on top of the Autorelease Pool Stack. Actually I'll have to try it out ;)

Thanks
It says "class method," not instance method.
Chuck