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:

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

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

About Jay Versluis

Jay is a medical miracle known as Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.