简体   繁体   中英

Prevent NSDocument-based app from reopening documents after a crash

I have a read-only music player app for macOS that uses NSDocument to get all the file-handling logic for free.

The problem that I now have is that every time the app crashes (or is stopped by the debugger) while one or more player windows are open, they automatically get reopened when the app is restarted. I don't want that, since it interferes with debugging and legitimate crashes don't really happen with this app.

Apple's NSDocument documentation contains nothing regarding the reopening of files, so I'm out of luck there. Is there a proper way to do this?

First create a subclass of NSDocumentController and make sure you create an instance of it in - (void)applicationWillFinishLaunching:(NSNotification *)notification so it becomes the sharedDocumentController. (see this question )

Then in you subclass override the restore method:

+ (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];
    }
}

Willeke的回答适用于XCode11。XCode-> Product-> Scheme-> Edit Scheme,然后选中复选框:启动应用程序而不进行状态还原

I have a read-only music player app for macOS that uses NSDocument to get all the file-handling logic for free.

The problem that I now have is that every time the app crashes (or is stopped by the debugger) while one or more player windows are open, they automatically get reopened when the app is restarted. I don't want that, since it interferes with debugging and legitimate crashes don't really happen with this app.

Apple's NSDocument documentation contains nothing regarding the reopening of files, so I'm out of luck there. Is there a proper way to do this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM