Search code examples
objective-ccocoacore-datacocoa-bindingskey-value-observing

Help with Key-Value-Observing


I need a bit of help with KVO, I'm about half way there. What I'm trying to do is trigger a method when something in an Tree Controller changes.

So I 'm using this code to register as a KVO.

[theObject addObserver: self
            forKeyPath: @"myKeyPath"
               options: NSKeyValueObservingOptionNew
               context: NULL];

But how do i trigger a method when the Key Path I am observing changes?

One extra question, when I add my self as an Observer I want the Key Path to be a Property in my Core Data model, Have I done that correctly?


Solution

  • Override observeValueForKeyPath:ofObject:change:context: to dispatch the method you wish to call.

    @interface Foo : NSObject {
        NSDictionary *dispatch;
        ...
    }
    @end
    @implementation Foo
    -(id)init {
        if (self = [super init]) {
            dispatch = [[NSDictionary dictionaryWithObjectsAndKeys:NSStringFromSelector(@selector(somethingHappenedTo:with:)),@"myKeyPath",...,nil] retain];
            ...
        }
    }
    ...
    - (void)observeValueForKeyPath:(NSString *)keyPath
                ofObject:(id)object
                change:(NSDictionary *)change
                context:(void *)context
    {
        SEL msg = NSSelectorFromString([dispatch objectForKey:keyPath]);
        if (msg) {
            [self performSelector:msg withObject:object withObject:keyPath];
        }
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
    ...
    

    See "Receiving Notification of a Change" for details.