Cocoa中的关键价值观察,反思变化属性

时间:2009-05-11 21:28:35

标签: objective-c cocoa key-value-observing

我在布尔属性上使用键值观察NSObject方法:

-(void)observeValueForKeyPath:(NSString *)keyPath
                     ofObject:(id)object
                       change:(NSDictionary *)change
                      context:(void *)context 

此关键路径值的最有趣部分是BOOL,它在YES / NO之间不断翻转。我从变更字典中获得的最多是善意的= 1.无论如何没有探测我正在观察的对象,看看实际的变化值是什么?

感谢。

2 个答案:

答案 0 :(得分:20)

首先,指定NSKeyValueObservingOptionNew:

[theObject addObserver: self
            forKeyPath: @"theKey"
               options: NSKeyValueObservingOptionNew
               context: NULL];

...然后,在你的观察者方法中:

-(void) observeValueForKeyPath: (NSString *)keyPath ofObject: (id) object
                        change: (NSDictionary *) change context: (void *) context
{
    BOOL newValue = [[change objectForKey: NSKeyValueChangeNewKey] boolValue];
}

理想情况下,在调用nil之前,您需要检查值是-boolValue(好吧,可能),但为了清楚起见,这里省略了。

答案 1 :(得分:19)

正如Jim Dovey所说,除了改变字典没有带来nil,而是null值,所以

NSLog(@"%@", [change description]); 

将导致类似:

{
    kind = 1;
    new = <null>;
    old = <null>;
}

如上所述,在空值上调用boolValue将导致错误

  

[NSNull boolValue]:无法识别的选择器发送到实例0xa0147020

为避免这种情况,必须检查nil是否为[NSNull null],如下所示:

if([change objectForKey:NSKeyValueChangeNewKey] != [NSNull null]) 
  BOOL newValue = [[change objectForKey: NSKeyValueChangeNewKey] boolValue];

id newValue;
if((newValue[change valueForKey: @"new"]) != [NSNull null]){
     BOOL newBOOL = [newValue boolValue];
}