Yan*_*ivH 5 macos nsnotifications nsworkspace macos-sierra
我正在尝试在后台进程中运行一个程序,该程序将注册系统中的每个关闭事件。
通过注册 NSWorkspaceWillPowerOffNotification 来实现此目的,如下所示:
#import <AppKit/AppKit.h>
@interface ShutDownHandler : NSObject <NSApplicationDelegate>
- (void)computerWillShutDownNotification:(NSNotification *)notification;
@end
int main(int argc, char* argv[]) {
NSNotificationCenter *notCenter;
notCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
ShutDownHandler* sdh = [ShutDownHandler new];
[NSApplication sharedApplication].delegate = sdh;
[notCenter addObserver:sdh
selector:@selector(computerWillShutDownNotification:)
name:NSWorkspaceWillPowerOffNotification
object:nil];
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[[NSFileManager defaultManager] createFileAtPath:@"./output.txt" contents:nil attributes:nil];
});
[[NSRunLoop currentRunLoop] run];
return 0;
}
@implementation ShutDownHandler
- (void)computerWillShutDownNotification:(NSNotification *)notification {
NSFileHandle* file = [NSFileHandle fileHandleForUpdatingAtPath: @"./output.txt"];
[file seekToEndOfFile];
NSDateFormatter* fmt = [NSDateFormatter new];
[fmt setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate* current = [NSDate date];
NSString* dateStr = [fmt stringFromDate:current];
[dateStr writeToFile:@"./output.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
return NSTerminateCancel;
}
@end
Run Code Online (Sandbox Code Playgroud)
由于某种我无法理解的原因, NSWorkspaceWillPowerOffNotification 处理程序永远不会被调用!
还将以下内容添加到我的 .plist 中:
<key>NSSupportsSuddenTermination</key>
<false/>
Run Code Online (Sandbox Code Playgroud)
但关闭系统时仍然没有通知注册。
知道为什么吗?
归档时间: |
|
查看次数: |
927 次 |
最近记录: |