How to check if the Main Window in your Mac App was closed

As is customary with other parts of Mac and iOS, the Main Window (or in fact any NSWindow) conforms to the NSWindowDelegate protocol. Sadly this isn’t mentioned in the class reference for NSWindow and you’ll have to guess.

The drill is the same:

  • hook up your window to a class as The Delegate
  • have the class conform to the protocol
  • implement the method you want to watch

In this example we’d like to see if our Main Window is being closed and react accordingly (for example, by closing down our super simple one window app). We’ll use AppDelegate as our Window Delegate:

@interface AppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate>

Now that we’re conforming to the protocol, let’s listen to the following:

#pragma mark - Window Delegate

- (void)windowWillClose:(NSNotification *)notification {
    NSWindow *currentWindow = notification.object;
    if ([currentWindow isEqualTo:self.window]) {
        // save context and exit
        [self saveAction:self];

The if statement is optional, but in essence we’re asking “is the window that’s being closed self.window” which AppDelegate already has a reference to. If that’s the case, then we go ahead and save our Managed Object Context and quit the app.

If your class is the NSWindow delegate for more than one window, give each an identifier and query it accordingly.

All that remains to be done is to hook up our window to AppDelegate as a delegate:

Screen Shot 2014-05-09 at 16.59.52

Leave a Reply