applicationWillTerminate 和 applicationShouldTerminate 在 macOS 上没有得到 运行?

applicationWillTerminate and applicationShouldTerminate don't get run on macOS?

我想在应用程序终止时做一些事情,所以我向我的 AppDelegate 添加了 applicationShouldTerminate:applicationWillTerminate 方法。但是,当我从 XCode 运行 我的应用程序然后按 ⌘Q 时,这两个方法都不会被调用。

现在我正在通过记录和调用 printf 进行测试,当我退出我的应用程序时,我在任何地方都看不到任何输出。 documentation 似乎表明这应该有效。 Google 没有产生任何有用的结果,搜索 GitHub 例如代码主要是 returns 观察其他应用程序被终止的应用程序。

为什么 applicationShouldTerminate:applicationWillTerminate 没有被调用?

这是我的应用委托中的那些方法实现:

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

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

(我还通过在 Xcode 中创建一个全新的项目进行了测试,您可以在 https://github.com/noahlt/TestTerminator 中找到它)。

我通过编辑 Info.plist 并将 Application can be killed immediately when user is shutting down or logging out 设置为 NO 来修复此问题。

Xcode 自动生成 applicationWillTerminate 的方法存根对我来说很奇怪,但由于这个 Info.plist 键,默认情况下它不起作用。为了以后参考,我是运行Xcode版本11.2.1(11B500)。

(在 Apple Developer forums 上找到了这个答案。)