Kor*_*nel 6 cocoa termination confirmation quit
我希望我的应用程序在退出之前要求确认,除非在关机或重启期间系统终止它(因为当OS X在午夜尝试应用安全更新时它会卡在"你确定吗?"消息框中) .
如何找到启动终止的内容?在[NSApp terminate:sender]发件人总是nil.
我的第一个想法是只在激活"退出"主菜单项时询问,但是用户也可以从Dock菜单终止应用程序或者在按住Cmd + Tab的同时按Cmd + Q,我想要求确认在这些情况下也是如此.
当系统即将关闭、重新启动或用户刚刚注销时,您可以收到通知。这不是一个普通的通知,而是一个工作区通知。
您可以像这样注册通知:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
//...more code...
self.powerOffRequestDate = [NSDate distantPast];
NSNotificationCenter *wsnCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
[wsnCenter addObserver:self
selector:@selector(workspaceWillPowerOff:)
name:NSWorkspaceWillPowerOffNotification
object:nil];
}
Run Code Online (Sandbox Code Playgroud)
在通知处理程序中,您应该保存日期:
- (void)workspaceWillPowerOff:(NSNotification *)notification
{
self.powerOffRequestDate = [NSDate new];
}
Run Code Online (Sandbox Code Playgroud)
添加
@property (atomic,strong,readwrite) NSDate *powerOffRequestDate;
Run Code Online (Sandbox Code Playgroud)
到适当的地方。
当您的应用程序被要求终止时,您应该获取该日期并检查计算机是否即将关闭。
if([self.powerOffRequestDate timeIntervalSinceNow] > -60*5) {
// shutdown immediately
} else {
// ask user
}
Run Code Online (Sandbox Code Playgroud)
我为以下边缘情况选择了 5 分钟的间隔:计算机应该关闭电源,但另一个应用程序取消了该关闭。您的应用程序仍在运行。10 分钟后,用户关闭您的应用程序。在这种情况下,应用程序应该询问用户。这有点黑客,但我认为这不是“疯狂的黑客”......
希望这可以帮助。