In objective-c manual it is written that something like
return [[[SomeClass alloc] init] autorelease];
can be done and then release is not necessary at any point, even not in the function that received this object. Who owns this object then? when will it be released?
The current
NSAutoreleasePooldoes and will take care of the releasing when drained.IBActioncalls get wrapped into anNSAutoreleasePoolthat gets drained after the call.For all non-IBAction calls the following would apply:
Say, you have these methods:
Consider another scenario:
As you can see the autoreleased string object did not even have to be used in or get returned to the scope in which the pool was created.
NSAutoreleasePools exist on a stack (one per thread) and autoreleased objects get owned by the pool that’s topmost at the time of the call to
autorelease.Update:
If you are dealing with a tight loop and want to keep the memory moderately low while not slowing down your loop, consider doing something like this:
However
NSAutoreleasePoolis highly optimized, so one pool per iteration usually isn’t much of a problem.To fully understand how NSAutoreleasePools work read this excellent article by Mike Ash