我正在开发一个 Cocoa 应用程序,我需要在应用程序关闭之前执行不同的操作。我需要知道应用程序何时因重启而关闭以及何时因关机而关闭。
通过 NSWorkspaceWillPowerOffNotification
,无论是重启还是关闭,应用都会收到通知。
有没有办法确定掉电的原因?
最佳答案
您可能不需要使用 NSWorkspaceWillPowerOffNotification
,您只需使用 applicationShouldTerminate:
委托(delegate)和下面的代码即可。如果系统正在重新启动/关闭或用户正在注销,您的应用程序无论如何都会终止。
来自 Apple 开发者论坛:How to determine if an application "quit"is because of a logout or restart/shutdown?
https://developer.apple.com/forums/thread/94126
//#import <Foundation/Foundation.h>
//#import <Carbon/Carbon.h> // for kEventParamReason
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
NSAppleEventDescriptor* appleEventDesc = [[NSAppleEventManager sharedAppleEventManager] currentAppleEvent];
NSAppleEventDescriptor* whyDesc = [appleEventDesc attributeDescriptorForKeyword:kEventParamReason];
OSType why = [whyDesc typeCodeValue];
switch (why) {
case kAEShutDown: {
NSLog(@"kAEShutDown");
break;
}
case kAERestart: {
NSLog(@"kAERestart");
break;
}
case kAEReallyLogOut: {
NSLog(@"kAEReallyLogOut");
break;
}
}
...
return NSTerminateNow;
}
关于macos - 如何判断 NSWorkspaceWillPowerOffNotification 是由重启还是关机引起的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7961507/
相关文章:
xml - 为什么没有 XMLNS 前缀的 XML 属性不等于具有相同本地名称的前缀属性?
html-agility-pack - html 敏捷包和文本中的三角括号
wpf - 从 DataTemplate 中的控件获取 GridViewColumn
wpf - 如何使用不在代码隐藏中的 XAML 绑定(bind) ListView ItemsSou
python - 从 cx_Oracle 内部使用 SQL*PLUS COPY?
validation - 如何验证电子商务网站的电子邮件地址?
ruby-on-rails-3 - Solr/太阳黑子/Rails 3 错误 : undefined