Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 371
Amy Avatar asked Nov 17 '25 18:11

Amy


1 Answers

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
        }
    }
like image 111
Leo Avatar answered Nov 20 '25 08:11

Leo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!