Search code examples
objective-cmacoscocoansapplicationnsapplication-delegate

applicationWillTerminate and applicationShouldTerminate don't get run on macOS?


I want to do some stuff when an application terminates, so I added applicationShouldTerminate: and applicationWillTerminate methods to my AppDelegate. However, when I run my app from XCode and then press ⌘Q, neither method gets called.

Now I'm testing by both logging and calling printf, and I don't see any output anywhere when I quit my app. The documentation seems to indicate that this should work. Google hasn't yielded anything useful, and searching GitHub for example code mostly returns applications that watch other applications getting terminated.

Why aren't applicationShouldTerminate: and applicationWillTerminate getting called?

Here's those method implementations in my app delegate:

- (NSApplicationTerminateReply)applicationShouldTerminate:(NSNotification *)aNotification {
    printf("printf applicationShouldTerminate");
    NSLog(@"NSLog applicationShouldTerminate");
    return NSTerminateNow;
}

- (void)applicationWillTerminate:(NSNotification *)aNotification {
    printf("printf applicationWillTerminate");
    NSLog(@"NSLog applicationWillTerminate");
}

(I've also tested by making a brand-new project in Xcode, which you can find at https://github.com/noahlt/TestTerminator).


Solution

  • I fixed this by editing Info.plist and setting Application can be killed immediately when user is shutting down or logging out to NO.

    screenshot of edited Info.plist

    It's pretty weird to me that Xcode autogenerates the method stub for applicationWillTerminate but by default it doesn't work due to this Info.plist key. For future reference, I am running Xcode Version 11.2.1 (11B500).

    (Found this answer on the Apple Developer forums.)