4

I have a NSDocument based application. I'd like to know when the application is about to quit to validate some things. I'd hoped there might be a method such as a applicationWillQuit, but looking through the docs for both NSDocument and NSApplication I can't find anything similar.

Joey FourSheds
  • 479
  • 1
  • 7
  • 18

2 Answers2

12

There is a notification you can use coming from your NSApplication:

NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
 [nc addObserver:self 
        selector:@selector(appWillTerminate:) 
            name:NSApplicationWillTerminateNotification 
          object:nil];

This is documented here: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/nsapplication_Class/Reference/Reference.html

By passing the object as nil your method is being called whenever an object fires the notification.

guitarflow
  • 2,930
  • 25
  • 38
  • 2
    NSApplicationWillTerminateNotification Posted by the terminate: method to indicate that the application will terminate. Posted only if the delegate method applicationShouldTerminate: returns YES. The notification object is sharedApplication. This notification does not contain a userInfo dictionary. – uchuugaka Feb 10 '13 at 14:14
  • 3
    Your app delegate can also determine if something should be done first in the applicationShouldTerminate delegate method. NSApplicationWillTerminateNotification only says it's going to happen. – uchuugaka Feb 10 '13 at 14:17
  • Yap, correct. `- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender` would be the method signature. – guitarflow Feb 10 '13 at 14:18
  • Thanks for the solution and link, exactly as needed. – Joey FourSheds Feb 11 '13 at 08:16
-1

We have a delegate method in AppDelegate.swift or AppDelegate.m class. You can use it and add functionality to you application before closing it.

func applicationWillTerminate(_ aNotification: Notification) {
    // Insert code here to tear down your application
}
Lakshmi Yadav
  • 156
  • 1
  • 10