如何从KVO方法observeValueForKeyPath:ofObject:change:context:中的更改字典中获取int值? [英] How can I get int values from the change dictionary in KVO method observeValueForKeyPath:ofObject:change:context:?
问题描述
我通过像这样调用以下方法来观察AVPlayer的rate
属性中的变化:
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];
因此,我从observeValueForKeyPath:ofObject:change:context:
获得的change
词典是:
The change
dictionary I get back from observeValueForKeyPath:ofObject:change:context:
is therefore:
change = { kind: 1,
new: 1,
old: 0 }
我检查了每个值的类,结果是__NSCFNumber.但是,当我尝试将[change objectForKey:@"new"]
或[change objectForKey:@"old"]
转换为int,NSInteger,NSNumber甚至尝试使用NSString等时,它适用于旧",但是却为我提供了新"的解析错误:>
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
我真的需要比较它们,我无法弄清楚.这可能是iOS中的错误吗?
I really need to compare them, and I can't figure it out. Could this be a bug in iOS?
推荐答案
目标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;
}
迅速
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
}
}
这篇关于如何从KVO方法observeValueForKeyPath:ofObject:change:context:中的更改字典中获取int值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!