今天在些项目的时候,遇到了一个界面是关于消息.具体的描述见图:

数据我用plist文件,见图:

那如何点击了带点的消息后,点就会消失呢?(变为已读状态,点击cell是可以跳转到消息详情的,但是这个不是本文所关注的)
我第一反应就是利用KVO来做,监听属性值的改变. 在数据中肯定会有一个字段来表示此消息是否已读或未读.既然想到用KVO来做,那我就高兴的写下去了,大致代码如下:

tableview的点击事件我用了代理,代码如下:

运行后一切正常,点击了未读的cell,也能如期看到结果,就在我pop回上一个界面的时候,我的内心是崩溃的,丫的...就给我崩了!-!...
崩的信息:

我就直接转向移除监听的代码,想着根据KVO的原则:观察一次解除一次;监听了几次就要解除几次,解除多了少了都不行.既然数据有3条,那我就遍历数据的数组,一个一个移除,那数组哪里来,难道在从tablevIew传进来,不可能吧! 我就谷歌了下,终于找到解决办法了!在这里我就记录下这样的知识点,和大伙们一起分享.
我就不直接累赘太多了,伙伴们可以去看这篇关于collectionviewCell的KVO的使用(UICollectionViewCell 使用 KVO 的正确方法)与yableViewCell的KVO的使用很类似,直接上代码:

至于监听实现的代码属于cell内部:
修改为以下代码:

最后在pop上一个界面时,还要移除屏幕能看到的所有cell所注册的:
修改处:

大致是这样,具体的解析,还是看以上那个链接的描述,这里也是很感谢
UICollectionViewCell 使用 KVO 的正确方法
作者提供的这个知识点.这里我只是代码具体化了!
网友评论
、、、
Terminating app due to uncaught exception 'NSRangeException', reason: 'Cannot remove an observer <MyJourneyTableViewCell 0x7fd17821da00> for the key path "acceptObject" from <JourneyModel 0x600000ee6480> because it is not registered as an observer.'
、、、
是为啥呢?