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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 13:20:05

问题


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?


回答1:


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
        }
    }



回答2:


Swift 3:

if let newValue = change?[NSKeyValueChangeKey.newKey] as? NSNumber {
     // Do stuff
}


来源:https://stackoverflow.com/questions/31486951/how-can-i-get-int-values-from-the-change-dictionary-in-kvo-method-observevaluefo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!