[英]How do I neatly bind Cocoa inputs to NSDocument properties?
假設我有一個簡單的 NSDocument 子類:
@interface Document : NSDocument
@property NSString *someText;
@end
我想 map someText
到我視圖中的某個字段 - 所以我向我的視圖 controller 添加一個新字段:
@interface ViewController : NSViewController
@property Document* document;
@end
...並確保存儲我的文檔:
- (void)setRepresentedObject:(id)representedObject {
[super setRepresentedObject:representedObject];
self.document = ((Document*)representedObject);
}
哦,是的,我確保文檔屬性是動態的,在谷歌上搜索一下,這對於數據綁定很重要:
@implementation Document
@dynamic someText;
@end
然后轉到我的 NSTextField 並嘗試綁定值:
如您所見,它報告“Xcode 無法解析輸入的密鑰路徑”。 此外,“控制器密鑰”字段(我相信我應該在其中指定document
,其中self.someText
為 self.someText ?)完全變灰。
我究竟做錯了什么?
事實證明, @dynamic
不是必需的——需要的是視圖控制器的representedObject
對象設置得相當早。
我修改了文檔 class 中默認生成的makeWindowControllers
,以便在調用addWindowController
之前在剛剛創建的 WindowController 的 contentViewController 上設置representedObject
對象:
- (void)makeWindowControllers {
NSWindowController *wc = [[NSStoryboard storyboardWithName:@"Main" bundle:nil] instantiateControllerWithIdentifier:@"Document Window Controller"];
wc.contentViewController.representedObject = self;
[self addWindowController:wc];
}
然后,在我的 storyboard 中,我簡單地綁定到View Controller
與 Model 的 Key Path 的representedObject.someText
Object.someText 。 (如果事情似乎仍然沒有改變,請務必選中“持續更新值” - 否則數據 model 可能僅在某些事件(例如焦點更改)時更新。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.