简体   繁体   中英

How to know when a Cocoa app is about to quit?

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.

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM