Key Value Observing in Cocoa, introspecting the change property

Coocoo4Cocoa picture Coocoo4Cocoa · May 11, 2009 · Viewed 12.1k times · Source

I'm using key value observing on a boolean property an NSObject method:

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

The most interesting part of the value for this key path is a BOOL which is constantly flipping between YES/NO. The most I get out of the change dictionary is kind = 1. Is there anyway without probing the object I'm observing to see what the actual change value is?

Thanks.

Answer

Jim Dovey picture Jim Dovey · May 11, 2009

Firstly, you specify NSKeyValueObservingOptionNew:

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

…then, in your observer method:

-(void) observeValueForKeyPath: (NSString *)keyPath ofObject: (id) object
                        change: (NSDictionary *) change context: (void *) context
{
    BOOL newValue = [[change objectForKey: NSKeyValueChangeNewKey] boolValue];
}

Ideally you'd check whether value was nil (well, it might happen) before calling -boolValue, but that was omitted for clarity here.