MatterGoal
MatterGoal

Reputation: 16430

Where is the autorelease pool for OS X application created and drained?

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:

My next question is:

Upvotes: 4

Views: 1235

Answers (2)

Tatiana Racheva
Tatiana Racheva

Reputation: 1304

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.

Upvotes: 1

user557219
user557219

Reputation:

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.

Upvotes: 6

Related Questions