簡體   English   中英

如何巧妙地將 Cocoa 輸入綁定到 NSDocument 屬性?

[英]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 綁定接口無法識別 Model Key Path 的截圖

如您所見,它報告“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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM