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
}
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With