我正在开发一个 Cocoa 应用程序,我需要在应用程序关闭之前执行不同的操作。我需要知道应用程序何时因重启而关闭,何时因关机而关闭。
NSWorkspaceWillPowerOffNotification
无论是重启还是关机,通过应用程序都会收到通知。
有没有办法确定断电的原因?
我正在开发一个 Cocoa 应用程序,我需要在应用程序关闭之前执行不同的操作。我需要知道应用程序何时因重启而关闭,何时因关机而关闭。
NSWorkspaceWillPowerOffNotification
无论是重启还是关机,通过应用程序都会收到通知。
有没有办法确定断电的原因?
您可能不需要使用NSWorkspaceWillPowerOffNotification
,您可以将applicationShouldTerminate:
委托与下面的代码一起使用。如果系统重新启动/关闭或用户正在注销,您的应用程序无论如何都会终止。
来自 Apple 开发者论坛:如何确定应用程序“退出”是因为注销还是重新启动/关闭?
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;
}