cocoaappkitnsdocumentnswindowcontroller

Under what conditions can an NSWindowController's document change?


My app observes the document property of its NSWindowController and performs some UI setup when it is set. Once it has been set, it would be difficult to rebuild the UI (for internal reasons) as the result of a change.

Once an NSWindowController has set its document property to an opened document, under what conditions will the system ever change that property to a new NSDocument instance (i.e., will the document ever be swapped out)? I've never observed it happening, but I can imagine features like versions or iCloud syncing causing the window controller's document to get swapped for a new document. However, the documentation on the NSWindowController lifecycle doesn't seem to touch on the issue.


Solution

  • It doesn't change once it has been set. NSWindowController gets its document by addWindowController method. Every new/opened document creates it's own windowController. Instance of document doesn't change with iCloud or revertChanges. It is up to you how to synchronise document with its views (redrawing).

    /* Create the user interface for this document, but don't show it yet. 
    The default implementation of this method invokes [self windowNibName], 
    creates a new window controller using the resulting nib name (if it is not nil), 
    specifying this document as the nib file's owner, and then invokes [self addWindowController:theNewWindowController] to attach it. You can override 
    this method to use a custom subclass of NSWindowController or to create more 
    than one window controller right away. NSDocumentController invokes this method 
    when creating or opening new documents.
    */
    
    
    // e.g. override 
    - (void)makeWindowControllers
    {
        if ([[self windowControllers] count] == 0) {
            MainWindowController *controller = [[MainWindowController alloc] init];
            [self addWindowController:controller];
        }
    }