views:

39

answers:

2

A beginner question here.

My goal: to understand the design rationale behind this.

When I created a Command Line tool project that links against Foundation class, xcode generated the following code snippet.

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...
    NSLog(@"Hello, World!");
    [pool drain];
    return 0;
}

I have some general idea of the functionality of NSAutoreleasePool. But I do not understand why we need NSAutoreleasePool here: in such a simple program, when main() finished, all alloc'd objects will be released anyway.

Is there other reason/advantage of having NSAutoreleasePool here?

+3  A: 

The autorelease pool has to exist for the memory management system to work at all. You're right that the [pool drain] is arguably unnecessary since the the OS will clean up all your program's memory when the process exits, but it is included for clarity (and strict correctness).

I think the hypothesis here is that you will probably add code that makes use of the autorelease pool, so they're just hoping to save you some typing.

Carl Norum
+1  A: 

You're correct that when you program exits it's memory will be reclaimed, but what if your program runs for days on end without exiting (a server or a daemon) and you have no auto release pool and you don't release your objects. What then? Your app will continue to consume memory until -bang- you run out of memory and your system crashes.

That's why the auto release pool is there.

Jasarien