Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access NSDocument from NSViewController and vice versa

What is the correct way to access the NSDocument subclass from its associated NSViewController subclass and vice versa?

I have the following code that does the former, but it doesn't work when the view has loaded or when it moved to a window:

var document: Document {
    return NSDocumentController.sharedDocumentController().documentForWindow(view.window!) as! Document
}
like image 734
Gor Gyolchanyan Avatar asked Dec 18 '22 19:12

Gor Gyolchanyan


1 Answers

Accessing NSDocument from NSViewController

The document can be accessed from the view controller via this property (Document is a subclass of NSDocument):

var document: Document? {
    return view.window?.windowController?.document as? Document
}

This property will return nil in the viewDidLoad method, but will return the document in the viewDidAppear method.

Accessing NSViewController from NSDocument

The view controller can be accessed from the document via this property (ViewController is a subclass of NSViewController):

var viewControllers: [ViewController] {
    var result: [ViewController] = []
    for windowController in windowControllers {
        if let viewController = windowController.contentViewController as? ViewController {
            result.append(viewController)
        }
    }
    return result
}

In case you only create one window controller in your makeWindowControllers method:

var viewController: ViewController? {
    return windowControllers[0].contentViewController as? ViewController
}
like image 64
Gor Gyolchanyan Avatar answered Feb 02 '23 06:02

Gor Gyolchanyan