如何从 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
属性 的变化:
addObserver:sharedPlayerManagerInstance
forKeyPath:@"rate"
options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld
context:0];
因此,我从 observeValueForKeyPath:ofObject:change:context:
得到的 change
字典是:
change = { kind: 1,
new: 1,
old: 0 }
我检查了每个值的class,原来是__NSCFNumber。但是,当我尝试将 [change objectForKey:@"new"]
或 [change objectForKey:@"old"]
转换为 int、NSInteger、NSNumber,甚至尝试过 NSString 等时,它对 "old" 有效,但它给了我一个解析错误"new":
error: expected a type
error: 1 errors parsing expression
真要对比一下,想不通。这可能是 iOS 中的错误吗?
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
}
}
Swift 3:
if let newValue = change?[NSKeyValueChangeKey.newKey] as? NSNumber {
// Do stuff
}
我正在通过调用以下方法来观察 AVPlayer rate
属性 的变化:
addObserver:sharedPlayerManagerInstance
forKeyPath:@"rate"
options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld
context:0];
因此,我从 observeValueForKeyPath:ofObject:change:context:
得到的 change
字典是:
change = { kind: 1,
new: 1,
old: 0 }
我检查了每个值的class,原来是__NSCFNumber。但是,当我尝试将 [change objectForKey:@"new"]
或 [change objectForKey:@"old"]
转换为 int、NSInteger、NSNumber,甚至尝试过 NSString 等时,它对 "old" 有效,但它给了我一个解析错误"new":
error: expected a type
error: 1 errors parsing expression
真要对比一下,想不通。这可能是 iOS 中的错误吗?
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
}
}
Swift 3:
if let newValue = change?[NSKeyValueChangeKey.newKey] as? NSNumber {
// Do stuff
}