4
votes

I'm refactoring my OS X application for ARC. Opening the main.m file, I was sure I would find the Autorelease Pool instantiation and drain (like iOS projects) but to my big surprise it wasn't there.

So my first question is:

  • Where is the main Autorelease Pool?

My next question is:

  • If the main Autorelease Pool isn't created, do I need to create it? Or are autoreleased objects freed in some automagical way?
2

2 Answers

6
votes

Your main.m file should have the following call:

NSApplicationMain(argc, (const char **)argv);

NSApplicationMain() is responsible for creating the application, i.e., an instance of NSApplication, which in turn is responsible for creating autorelease pools:

The NSApplication class sets up autorelease pools (instances of the NSAutoreleasePool class) during initialization and inside the event loop—specifically, within its initialization (or sharedApplication) and run methods.

This means that, in the general case, you shouldn’t have to worry about creating autorelease pools since NSApplication already does that in both the initialisation and in the event loop. There are situations where creating your own autorelease pools might be necessary/desirable, e.g. a method that has a loop that creates many autoreleased objects. In this case, it’s a good idea to have an autorelease pool for each loop iteration.

1
votes

As is often the case, this topic is very well-covered in Apple's documentation. For example, check out the What Happens in the main Function section of this Cocoa Fundamentals Guide chapter. To quote the part relevant to this question (already explained by Bavarious):

The main function in almost all Cocoa applications is extremely simple. In Mac OS X, it consists of only one function call.

#import <AppKit/AppKit.h>

int main(int argc, const char *argv[]) {
    return NSApplicationMain(argc, argv);
}

The NSApplicationMain function creates the application object, sets up an autorelease pool, loads the initial user interface from the main nib file, and runs the application, thereby requesting it to begin handling events received on the main event loop.