>我正在尝试实现键值观察模式,并且在大多数情况下过程运行良好,但是即使值已从旧值更改为新值,我的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
.