实施有问题的 KeyValue Observation

Implementing KeyValue Observation with issues

我正在尝试实施键值观察模式,并且在大多数过程中运行良好,但我的 newValue 和 oldValue 是相同的,即使值已从旧值更改为新值。这是我到目前为止实现的示例代码。如果有人能告诉我哪里做错了就太好了。

@property (strong, nonatomic) NSString* selectedRow; 

添加观察者

 [self addObserver:self
           forKeyPath:@"selectedRow"
              options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
              context:NULL];

更新值的方法

-(void) methodToChangeValue {
self.selectedRow = [self.tableView indexPathForCell:[selectedCell]];
//Above line is dummy that will get the row for indexPath and set the selected row, I wanted to pass that row to selectRow key

}

观察者呼叫

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

    NSString* oldValue = [change valueForKey:NSKeyValueChangeOldKey];
    NSString *newValue = [change valueForKey:NSKeyValueChangeNewKey];

    NSLog(@" old value %@ and new value %@", oldValue,newValue);
}

** 尽管我从方法中更改了值,但旧值和新值相同。

谢谢

你的问题是这些行:

_selectedRow = [self.tableView indexPathForCell:[selectedCell]];
[self setValue:_selectedRow forKey:@"selectedRow"];

你为什么要这样做?为什么不以正确的方式进行:

self.selectedRow = [self.tableView indexPathForCell:[selectedCell]];

如果你这样做,KVO 将正常工作。正如您现在所拥有的,您直接设置实例变量(绕过 KVO),然后使用 KVC 将 属性 设置为与其自身实例变量相同的值。由于您将 属性 设置为它自己的值,因此您的观察者认为旧值和新值相同。

您还为 selectedRow 使用了错误的数据类型。它需要 NSIndexPath 而不是 NSString。获取旧值和新值相同。使用 NSIndexPath.