Why use NSAutoreleasePool?

But if i don't want to auto release any object, then also do i need to use Auto Release pool ??

Also note that the Cocoa library uses autorelease extensively. So, even if you think you don't use the pool in your code, you need to prepare the pool.


NSObject contains a neat function called autorelease. This means all objects in Objective-C contain this function.

This function inserts self into the autorelease pool, delaying the call to object's release function until the autorelease pool is deallocated. Most internal APIs use an autorelease pool, and beside the one located in main(), there is one allocated and deallocated in UIKit's main loop in every pass.

In short: it's the queue for delayed decrement of reference counter.

Example on where autorelease is hidden:

[NSString stringWithUTF8String:"some string"];

This object is allocated, and autorelease is called on it. How would you use it yourself?

MyObject *obj = [[[MyClass alloc] init] autorelease];

Why is this good? When you return this object, the calling function does not need to take care to release this object, and optionally it can retain it (but doesn't have to).


To expand and clarify four years later:

While UIKit and AppKit create and drain an NSAutoreleasePool during the course of their main runloop, in your non-GUI program you need to create it yourself. Various code expects having an NSAutoreleasePool present, and since you didn't initialize a GUI framework nor you use one, there is no code that will magically create it for you.

While NSLog() and a constant NSString in your example don't require a pool, even the trivial [NSMutableArray array] does, given that it can actually be interpreted as [[[NSMutableArray alloc] init] autorelease].

Tags:

Objective C