11
votes

How correctly to quit the Mac OS X app, when the main (the only one) closes?

I know there a method - (void)windowWillClose:(NSNotification *)notification in NSWindowDelegate. But it isn't quite suitable in my case, because it is called before NSWindow closes.

1

1 Answers

32
votes

You cannot have windowDidClose event since the notification that accompanies it would be holding an invalid object (the window is likely to have been deallocated on close). To achieve what you need, make your class the delegate of the Application, and implement the following method:

- (BOOL) applicationShouldTerminateAfterLastWindowClosed: (NSApplication *) theApplication;

From that method, return YES.

If your controller object has an instance in the MainMenu.nib, just make a connection from File's Owner (which means Application Object in the MainMenu.nob file). Control-Drag from File's Owner to your object, and connect the delegate outlet.

Or in source code, put something like this in your controller object's init method:

[NSApp setDelegate: self];