At launch, prevent a document-based app to reopen an unsaved-unedited-empty document that was opened when quit

172 views Asked by At

In a simple rtf editor —based on NSDocument subclass—, when app starts, it creates an untitled file. This a desirable behaviour. But if I quit the app with this opened, unedited and unsaved document (empty!), the application will restore this document at the next launch.

How can I set this document so that it cannot be restored. If I uncheck the window's controller window "Restorable" property in IB, no document is restored ever, which is not the desirable behaviour: edited-saved documents that were not closed by user need being restored; untitled-unedited documents should not!

1

There are 1 answers

0
Denis On

I found a solution. First, I subclassed NSDocumentController and added in its implementation file:

+ (void)restoreWindowWithIdentifier:(NSString *)identifier state:(NSCoder *)state completionHandler:(void (^)(NSWindow *, NSError *))completionHandler
{
    NSInteger restorable = [state decodeIntegerForKey:@"restorable"];
    if (!restorable) {
        completionHandler(nil, [NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]);
    }
    else {
        [super restoreWindowWithIdentifier:identifier state:state completionHandler:completionHandler];
    }
}

Then I added code in my NSDocument subclass implementation file

- (void) encodeRestorableStateWithCoder:(NSCoder *) coder {

    if (self.fileURL){
        [coder encodeInteger:1 forKey:@"restorable"];
    } else {
        [coder encodeInteger:0 forKey:@"restorable"];
    }
    [super encodeRestorableStateWithCoder:coder];
}

So the flag is set to 0 for any untitled document with a nil fileURL and there will be no restoration a launch. Other documents are restored.