gpt4 book ai didi

ios - 实现有问题的 KeyValue Observation

转载 作者:行者123 更新时间:2023-11-29 00:30:49 25 4
gpt4 key购买 nike

我正在尝试实现键值观察模式,并且在大多数情况下该过程运行良好,但我的 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

关于ios - 实现有问题的 KeyValue Observation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41902960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com