Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use NSAutoreleasePool?

Tags:

objective-c

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 ?

like image 635
Matrix Avatar asked Sep 07 '10 13:09

Matrix


2 Answers

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

  • Autorelease Pools and Ownership and Disposal
like image 160
miku Avatar answered Sep 17 '22 01:09

miku


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

like image 28
Ivan Vučica Avatar answered Sep 20 '22 01:09

Ivan Vučica