开发者

Xcode, Command line tool: Why NSAutoreleasePool is in the generated template?

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜