防止基于 NSDocument 的应用程序在崩溃后重新打开文档

Pet*_* W. 1 cocoa nsdocument swift

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

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

苹果的 NSDocument 文档不包含任何有关重新打开文件的内容,所以我在那里运气不好。有没有正确的方法来做到这一点?

pfa*_*ade 5

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

然后在你的子类中重写恢复方法:

+ (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];
    }
}
Run Code Online (Sandbox Code Playgroud)