如何从KVO方法observeValueForKeyPath:ofObject中的更改字典中获取int值:change:context:?

时间:2015-07-18 01:44:11

标签: ios objective-c nsdictionary key-value-observing key-value-coding

我通过调用以下方法来观察AVPlayer的#include <cstdio> void __fastcall TForm1::Button1Click(TObject *Sender) { int number; if (std::swscanf(Edit1->Text.c_str(), L"%d", &number) == 1) { // use number as needed... ShowMessage("It is a number"); } else { // not a number, do something else... ShowMessage("It is not a number"); } } 属性的变化,如下所示:

rate

我从addObserver:sharedPlayerManagerInstance forKeyPath:@"rate" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:0]; 返回的change词典是:

observeValueForKeyPath:ofObject:change:context:

我检查了每个值的类,结果是__NSCFNumber。但是,当我尝试将change = { kind: 1, new: 1, old: 0 } [change objectForKey:@"new"]转换为int,NSInteger,NSNumber,甚至尝试过NSString等时,它适用于&#34; old&#34;,但它给了我一个解析&#34; new&#34;:

的错误
[change objectForKey:@"old"]

我真的需要比较它们,我无法弄明白。这可能是iOS中的错误吗?

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

斯威夫特3:

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