首页 > 解决方案 > 防止基于 NSDocument 的应用程序在崩溃后重新打开文档

问题描述

我有一个适用于 macOS 的只读音乐播放器应用程序,它使用 NSDocument 免费获取所有文件处理逻辑。

我现在遇到的问题是,每次在打开一个或多个播放器窗口时应用程序崩溃(或被调试器停止)时,它们会在应用程序重新启动时自动重新打开。我不希望这样,因为它会干扰调试,并且此应用程序不会真正发生合法崩溃。

Apple 的 NSDocument 文档没有包含任何关于重新打开文件的内容,所以我不走运。有没有合适的方法来做到这一点?

标签: swiftcocoansdocument

解决方案


首先创建一个子类NSDocumentController并确保在其中创建它的一个实例,- (void)applicationWillFinishLaunching:(NSNotification *)notification以便它成为 sharedDocumentController。(见这个问题

然后在你的子类中覆盖 restore 方法:

+ (void)restoreWindowWithIdentifier:(NSString *)identifier state:(NSCoder *)state completionHandler:(void (^)(NSWindow *, NSError *))completionHandler
{
    if (_preventDocumentRestoration) { // you need to decide when this var is true
        completionHandler(nil, [NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]);
    }
    else {
        [super restoreWindowWithIdentifier:identifier state:state completionHandler:completionHandler];
    }
}

推荐阅读