Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mac App Storyboard - Access Document in NSViewController

Tags:

I am currently fighting with NSDocument in a document based Storyboard based Cocoa Application (Objective C). Can anybody tell me how i can access the document in the NSViewController subclass?

I've tried to access it the following way - but the document is null:

[self.view.window.windowController document];

Thanks for your help!

Best regards Martin

like image 620
Martin Avatar asked Dec 30 '14 08:12

Martin


2 Answers

I was just wrestling with this myself. I started with the standard Yosemite template and was trying to use [self.view.window.windowController document] in -viewDidLoad. At that point, self.view.window is nil, so there's no way to get to the document.

The trick is to wait until -viewWillAppear. By the time it is called, self.view.window is populated and the document is available.

Sequence: -makeWindowControllers invokes -self addWindowController: with the storyboard's -instantiateControllerWithIdentifier: result. -addWindowController: triggers a call to the VC's -viewDidLoad before returning. Then, finally, -viewWillAppear is called (and the document is available).

like image 115
Hal Mueller Avatar answered Jan 12 '23 08:01

Hal Mueller


This does not directly address the question. But the Q&A link below shows how to access the data model in your document from NSControl objects using bindings, by utilising the preparedObject of the NSViewController.

https://developer.apple.com/library/content/qa/qa1871/_index.html

I set the representedObject for the NSViewController in Document.m as following:

- (void)makeWindowControllers {
    NSWindowController* wc = [[NSStoryboard storyboardWithName:@"Main" bundle:nil] instantiateControllerWithIdentifier:@"Document Window Controller"];
    NSViewController* vc = wc.contentViewController;
    vc.representedObject = self.model;

    [self addWindowController:wc];
}

Now representedObject of my ViewController is set to model. Assuming my model has a text property, I can bind any NSControl to that property through ViewController with keyPath: self.representedObject.text

like image 21
Chester Beaty Avatar answered Jan 12 '23 08:01

Chester Beaty