2014-01-10 72 views
1

我有一個NSView其中所有的控件已被綁定到模型對象使用Interface Builder中的NSObjectController如何通知任何綁定更改爲NSObjectController

這工作正常。現在,我希望我的NSViewController每當發生這些綁定的任何更改時都會收到通知。這可能嗎?如果是這樣,怎麼樣?

回答

0

我最終觀察了使用KVO的模型類的成員。爲了使程序自動化(以便我不必爲每個模型的每個成員編寫代碼)我這樣做:

static void *myModelObserverContextPointer = &myModelObserverContextPointer; 

- (void)establishObserversForPanelModel:(FTDisclosurePanelModel *)panelModel { 

    // Add observers for all the model's class members. 
    // 
    // The member variables are updated automatically using bindings as the user makes 
    // adjustments to the user interface. By doing this we can therefore be informed 
    // of any changes that the user is making without having to have a target action for 
    // each control. 

    unsigned int count; 
    objc_property_t *props = class_copyPropertyList([panelModel class], &count); 

    for (int i = 0; i < count; ++i){ 
     NSString *propName = [NSString stringWithUTF8String:property_getName(props[i])]; 
     [panelModel addObserver:self forKeyPath:propName options:0 context:&myModelObserverContextPointer]; 
    } 
} 

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { 

    // Check for insertions/deletions to the model 

    if (context == myModelObserverContextPointer) { 
     if ([_delegate respondsToSelector:@selector(changeMadeToPanelModel:keyPath:)]) { 
      [_delegate changeMadeToPanelModel:object keyPath:keyPath]; 
     } 
    } 
    else 
     [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; 

} 
相關問題