Mac App Storyboard - 在NSViewController中访问文档

Mar*_*tin 21 macos cocoa objective-c storyboard

我目前正在基于基于故事板的Cocoa应用程序(目标C)中与NSDocument进行斗争.任何人都可以告诉我如何在NSViewController子类中访问该文档?

我试图通过以下方式访问它 - 但文档为null:

[self.view.window.windowController document];
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

最好的问候马丁

Hal*_*ler 18

我自己也只是在摔跤.我开始与标准约塞米蒂模板,并试图用[self.view.window.windowController document]-viewDidLoad.那时,self.view.windownil,所以没有办法到达document.

诀窍是等到-viewWillAppear.当它被调用时,self.view.window填充并且document可用.

顺序:-makeWindowControllers调用-self addWindowController:故事板的instantiateControllerWithIdentifier:结果.在返回之前-addWindowController:触发对VC的调用-viewDidLoad.然后,最后,-viewWillAppear被调用(并且document可用).


小智 5

这不能直接解决问题。但是下面的Q&A链接显示了如何利用NSViewController的prepareObject从绑定使用NSControl对象访问文档中的数据模型。

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

我在Document.m中为NSViewController设置了presentatedObject,如下所示:

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

    [self addWindowController:wc];
}
Run Code Online (Sandbox Code Playgroud)

现在,我的ViewController的presentatedObject设置为模型。假设我的模型具有text属性,则可以使用keyPath通过ViewController将任何NSControl绑定到该属性:self.representedObject.text