3

I have an NSDocument based app in which I want to limit the number of documents open at the same time (for a Lite version). I just want to have n documents, and if the user tries to open more than n, show a message with a link to the full app download.

I have managed to count the number of documents using NSDocumentController and, inside readFromFileWrapper, I can return FALSE. That prevents the new doc from opening, but it shows a standard error message. I don't know how to avoid that. I would like to open a new window from a nib.

Is there any way to prevent NSDocument showing the standard error message when returning FALSE from readFromFileWrapper? Or is there any other way to prevent the document from opening before readFromFileWrapper is called?

Cajunluke
  • 3,103
  • 28
  • 28
Ernesto
  • 510
  • 3
  • 10

1 Answers1

5

Try the init method, which is called both when creating a new document and when opening a saved document. You simply return nil if the limit has been reached. However, I have not tried this, and it might cause the same error to be displayed.

- (id)init {
    if([[NSDocumentController documents] count] >= DOCUMENT_LIMIT) {
        [self release];
        return nil;
    }
    ...
}

In case the same error is displayed, you could use a custom NSDocumentController. Your implementations would check the number of open documents, display the message at the limit, and call the normal implementation otherwise.

- (id)openUntitledDocumentAndDisplay:(BOOL)displayDocument error:(NSError **)outError {
    if([[self documents] count] >= DOCUMENT_LIMIT) {
        // fill outError
        return nil;
    }
    return [super openUntitledDocumentAndDisplay:displayDocument error:outError];
}
- (id)openDocumentWithContentsOfURL:(NSURL *)absoluteURL display:(BOOL)displayDocument error:(NSError **)outError {
    NSDocument *doc = [self documentForURL:absoluteURL];
    if(doc) { // already open, just show it
        [doc showWindows];
        return doc;
    }
    if([[self documents] count] >= DOCUMENT_LIMIT) {
        // fill outError
        return nil;
    }
    return [super openDocumentWithContentsOfURL:absoluteURL display:displayDocument];
}
ughoavgfhw
  • 39,734
  • 6
  • 101
  • 123
  • 1
    Great. You pointed me in the right direction. I used your code, with openDocumentWithContentsOfURL, and i could prevent the document creation. But the warning message still appeared when i returned nil. Finally i solved it by overriding "presentError". It the error is my "max documents reached", I show my custom window. Else, i call [super presentError] to show the standard error message. Thanks a lot for your help. – Ernesto Apr 01 '11 at 08:18