4

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

现在我正在通过 logging 和 calls 进行测试,printf当我退出我的应用程序时,我在任何地方都看不到任何输出。该文档似乎表明这应该有效。谷歌没有产生任何有用的东西,在 GitHub 上搜索示例代码大多会返回观察其他应用程序被终止的应用程序。

为什么不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找到该项目)。

4

1 回答 1

4

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.)

于 2020-01-16T00:26:40.877 回答