Cocoa 应用程序是否有任何方法可以检测用户何时尝试通过 Dock 菜单退出它,而不是通过其他方法?
通常,可以使用应用程序委托的
applicationShouldTerminate:
方法捕获并响应退出事件。
但是,此方法似乎无法区分来自应用程序主菜单、Dock 图标、Apple 事件或任何其他退出应用程序的传统方法的退出请求。
事实上,应用程序可以通过检查是否有当前正在处理的 AppleEvent 来了解其退出的原因,如果有,则检查它是否是退出事件以及是否是 Dock 发送的事件。 (请参阅此线程讨论如何判断应用程序是否因为系统正在注销或关闭而退出。)
这是一个方法示例,当从应用程序委托的
applicationShouldTerminate:
方法调用时,如果应用程序通过 Dock 退出,则该方法将返回 true:
- (bool)isAppQuittingViaDock {
NSAppleEventDescriptor *appleEvent = [[NSAppleEventManager sharedAppleEventManager] currentAppleEvent];
if (!appleEvent) {
// No Apple event, so the app is not being quit by the Dock.
return false;
}
if ([appleEvent eventClass] != kCoreEventClass || [appleEvent eventID] != kAEQuitApplication) {
// Not a 'quit' event
return false;
}
NSAppleEventDescriptor *reason = [appleEvent attributeDescriptorForKeyword:kAEQuitReason];
if (reason) {
// If there is a reason for this 'quit' Apple event (such as the current user is logging out)
// then it didn't occur because the user quit the app through the Dock.
return false;
}
pid_t senderPID = [[appleEvent attributeDescriptorForKeyword:keySenderPIDAttr] int32Value];
if (senderPID == 0) {
return false;
}
NSRunningApplication *sender = [NSRunningApplication runningApplicationWithProcessIdentifier:senderPID];
if (!sender) {
return false;
}
return [@"com.apple.dock" isEqualToString:[sender bundleIdentifier]];
}