1

I have an NSView which in which all the controls have been bound to a model object using an NSObjectController in Interface Builder.

This works correctly. Now I would like my NSViewController to be notified whenever there's a change to any of those bindings. Is this possible? If so, how?

tarmes
  • 15,366
  • 10
  • 53
  • 87

1 Answers1

0

I ended up observing the member of my model class using KVO. To automate the process (so that I don't have to write code to do this for each member of each model) I did this:

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

}
rdougan
  • 7,217
  • 2
  • 34
  • 63
tarmes
  • 15,366
  • 10
  • 53
  • 87