tags:

views:

103

answers:

5

Consider the following program:

int main (int argc, const char * argv[]) { 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
    // Insert code here... 
    NSLog(@"Programming is Fun !"); 
    [pool drain]; 
    return 0;
}

I don't understand why pool is needed there as the same program can be also written as this:

int main (int argc, const char * argv[]) { 
    NSLog(@"Programming is Fun !"); 
    return 0;
}

What is a purpose of using an auto release pool? Why and when do we need them? Are they mandatory in every objective C program?

If i don't want to auto release any object, do I also need to use an Auto Release pool ?

A: 

Check out the NSAutoreleasePool documentation

Jeff
A: 

A general introduction can be found on Apple's website:

The MYYN
A: 

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).

Ivan Vučica
A: 

I have found reason... "If a pool is not available, autoreleased objects do not get released and you leak memory. In this situation, your program will typically log suitable warning messages."

Matrix
If you find some other answer particularly helpful, feel free to "up" it, and/or mark it as correct.
Ivan Vučica
+5  A: 

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.

Yuji