【问题标题】:NSDocumentController closeAllDocumentsWithDelegate does not call canCloseDocumentWithDelegate of my NSPersistentDocument subclassNSDocumentController closeAllDocumentsWithDelegate 不调用我的 NSPersistentDocument 子类的 canCloseDocumentWithDelegate
【发布时间】:2020-05-19 03:19:57
【问题描述】:
根据 Apple 的文档,如果您退出应用程序,对于所有打开的文档,closeAllDocumentsWithDelegate(来自 NSDocumentController)应该调用 canCloseDocumentWithDelegate 或 NSDocument。
在我的基于NSPersistentDocument 的应用程序中,我需要覆盖canCloseDocumentWithDelegate,以便在文档关闭时某个服务器功能仍在运行时向用户发出警告。这与任何数据更改无关。
这在用户关闭单个文档时有效;我可以出示一张带有警告的工作表,让用户取消关闭过程。
但是,当应用程序退出时,我的 canCloseDocumentWithDelegate 版本不会被调用。这可能是什么原因?
【问题讨论】:
标签:
macos
cocoa
nsdocument
nspersistentdocument
【解决方案1】:
根据 Apple 开发人员技术支持,这是一个已知问题。我终于把app的退出菜单项的自动连线剪掉了,自己处理。我需要使文档的服务器功能信息从外部可用(在本例中为optionButton 的状态)并将此功能添加到AppDelegate:
- (IBAction)terminateGracefully:(id)sender {
BOOL optionOn = FALSE;
for (Document *doc in NSApp.orderedDocuments) {
if (doc.optionButton.state == NSControlStateValueOn) {
optionOn = TRUE;
}
}
if (optionOn) {
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:@"Checkbox in some window is on"];
[alert setInformativeText:@"Something is going on. If you close the app now, it will stop. Close anyway?\n"];
[alert setAlertStyle:NSAlertStyleCritical];
[alert addButtonWithTitle:@"Don't close"];
[alert addButtonWithTitle:@"Close anyway"];
NSModalResponse resp = [alert runModal];
if (resp == NSAlertSecondButtonReturn) {
// We really want to close
[NSApp terminate:sender];
}
} else {
[NSApp terminate:sender];
}
}
然后我将应用的退出菜单项绑定到terminateGracefully: