1

我有一个NSView其中所有控件都使用NSObjectControllerInterface Builder 绑定到模型对象的其中。

这可以正常工作。现在,我希望在任何这些绑定NSViewController发生更改时得到通知。这可能吗?如果是这样,怎么做?

4

1 回答 1

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];

}
于 2014-01-10T14:08:10.027 回答