Search code examples
iosobjective-cnsdictionarykey-value-observingkey-value-coding

How can I get int values from the change dictionary in KVO method observeValueForKeyPath:ofObject:change:context:?


I am observing changes in the rate property of an AVPlayer by calling the following method on it like so:

addObserver:sharedPlayerManagerInstance
 forKeyPath:@"rate"
    options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld
    context:0]; 

The change dictionary I get back from observeValueForKeyPath:ofObject:change:context: is therefore:

change = { kind: 1,
            new: 1,
            old: 0 }

I checked the class of each value, and it turns out to be __NSCFNumber. However, when I try to convert [change objectForKey:@"new"] or [change objectForKey:@"old"] into an int, NSInteger, NSNumber, even tried NSString, etc, it works for "old", but it gives me a parsing error for the "new":

error: expected a type
error: 1 errors parsing expression

I really need to compare them, and I can't figure it out. Could this be a bug in iOS?


Solution

  • Objective C

    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    NSNumber * newValue = [change objectForKey:NSKeyValueChangeNewKey];
    NSInteger integerValue = newValue.integerValue;
    int intValue = newValue.intValue;
    }
    

    Swift

       override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
            if let newValue = change[NSKeyValueChangeNewKey] as? NSNumber{
                let intvalue = newValue.intValue //To int
            }
        }