KVO常见错误

KVO的常见错误

  • 1.remove观察者
*** Terminating app due to uncaught exception 'NSRangeException', reason: 'Cannot remove an observer <SubViewController 0x7ff158707f80> for the key path "age" from <SubViewController 0x7ff158707f80> because it is not registered as an observer.'

修改前代码

// 添加观察者
    Person *person = [[Person alloc] init];
    person.name = @"hello";
    person.age = 23;
    self.subPersonKVO = person;
    [self.subPersonKVO addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@"SubViewController"];
// 移除观察者 在dealloc中
    [self removeObserver:self forKeyPath:@"age" context:@"SubViewController"];

=============
解决方案

// 移除观察者 在dealloc中
    [self.subPersonKVO removeObserver:self forKeyPath:@"age" context:@"SubViewController"];

self -> self.subPersonKVO 关键点就在这里,观察谁,谁就应该移除

  • 2.值修改了,但是并没有接收到
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '<SubViewController: 0x7fc273d13450>: An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.
Key path: age

解决方案:添加该方法

`- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    NSLog(@"keyPath=%@", keyPath);
    self.subLabelKVO.text = [NSString stringWithFormat:@"%@现在的年龄是: %zd", self.subPersonKVO.name, self.subPersonKVO.age];
}
  • 3.context上下文不一致,也可以理解为标识符不统一
*** Terminating app due to uncaught exception 'NSRangeException', reason: 'Cannot remove an observer <SubViewController 0x7fc175001d60> for the key path "age" from <Person 0x7fc172da5be0> because it is not registered as an observer.'

修改前

`- (void) kvo {
Person *person = [[Person alloc] init];
    person.name = @"hello";
    person.age = 23;
    self.subPersonKVO = person;
    [self.subPersonKVO addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@"SubViewController"];
}
`- (void)dealloc {
    [self.subPersonKVO removeObserver:self forKeyPath:@"age" context:nil];
}

======
解决方案:context 统一

`- (void)dealloc {
    [self.subPersonKVO removeObserver:self forKeyPath:@"age" context:@"SubViewController"];
}

一般来说context都是nil,但是个人还是觉得区别开来为好
项目地址:https://github.com/wosta/OLKVO-KVC

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 设计模式是什么? 你知道哪些设计模式,并简要叙述? 设计模式是一种编码经验,就是用比较成熟的逻辑去处理某一种类型的...
    iOS菜鸟大大阅读 814评论 0 1
  • 1.设计模式是什么? 你知道哪些设计模式,并简要叙述? 设计模式是一种编码经验,就是用比较成熟的逻辑去处理某一种类...
    司马DE晴空阅读 1,479评论 0 7
  • KVC(Key-valuecoding)键值编码,单看这个名字可能不太好理解。其实翻译一下就很简单了,就是指iOS...
    榕樹頭阅读 772评论 0 2
  • 设计模式是什么? 你知道哪些设计模式,并简要叙述? 设计模式是一种编码经验,就是用比较成熟的逻辑去处理某一种类型的...
    Jt_Self阅读 836评论 0 4
  • 我一直在路上,在奔腾不息的方向
    杨格兰阅读 153评论 0 1

友情链接更多精彩内容