1

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?

Peter W.
  • 2,323
  • 4
  • 22
  • 42
  • I would suggest looking into something in the appDelegate file. If I remember correctly, you can put certain things into there to handle crashing and other similar things. – E. Huckabee Sep 11 '18 at 10:41
  • Stopping the debugger sends a SIGKILL, which is uncatchable, and applicationDidFinishLaunching is called before the document reopening happens, so no dice. – Peter W. Sep 11 '18 at 10:42
  • Try Xcode -> Edit Scheme -> Run -> Options -> Launch application without state restoration. – Willeke Sep 11 '18 at 14:34
  • That's only valid for the current debugging session, I want it to be disabled for my app only, and forever. – Peter W. Sep 12 '18 at 08:17
  • Possible duplicate of [Prevent "Resume" for my Cocoa application?](https://stackoverflow.com/questions/7466824/prevent-resume-for-my-cocoa-application) – Willeke Sep 13 '18 at 14:53

1 Answers1

5

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];
    }
}
pfandrade
  • 2,359
  • 15
  • 25