emmalyx
emmalyx

Reputation: 2356

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?

Upvotes: 1

Views: 1059

Answers (1)

pfandrade
pfandrade

Reputation: 2419

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

Upvotes: 5

Related Questions