ios - 我应该在哪里添加和删除 UICollectionViewCell 中的观察者?

标签 ios swift uicollectionview uicollectionviewcell key-value-observing

我对 UICollectionViewCell 生命周期的理解中缺少一些东西。

当创建和配置 UICollectionViewCell 时,我在其属性之一上添加观察者

func setCellDetails(someDetails:SomeObject)
{
    ...
    self.someProperty.addObserver(self, forKeyPath: "objectProperty", options: .New, context: nil)
    ...
}

我在 prepareForReuse 上删除了观察者

override func prepareForReuse()
{
    super.prepareForReuse()
    self.someProperty.removeObserver(self, forKeyPath: "objectProperty")
}

但是当我在应用程序的选项卡之间跳转并影响 objectProperty 时,单元格不会受到影响。 我调试了代码,发现当我更改选项卡时,单元格的 prepareForReuse 被调用,因此观察者被删除并且它永远不会添加回去,因为单元格设置函数没有被调用。所以也许我应该在其他功能中添加或删除观察者?


我试图将 removeObserver 放入 deinit 中,它崩溃并出现以下错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'An instance 0x12eb89dd0 of class ObservedObject was deallocated while key value observers were still registered with it. Current observation info: NSKeyValueObservationInfo NSKeyValueObservance Observer: .. Key path: objectProperty

我想也许不要把 removeObserver 放在任何地方。它产生了同样的错误。

我该怎么办?我应该把它放在哪里?

最佳答案

尝试从 Collection View 的委托(delegate)方法中移除观察者:- collectionView:didEndDisplayingCell:forItemAtIndexPath:

关于ios - 我应该在哪里添加和删除 UICollectionViewCell 中的观察者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35036086/

相关文章:

swift - 不使用预定义函数反转字符串

ios - Adobe Creative SDK iOS Swift 'AdobeImageEditorPremiumAddOn' 不可用错误

ios - 条形码未生成

ios - UICollectionViewController 的自定义弹出动画不起作用

ios - 选择 UICollectionViewCell 并获取 indexPath 可以通过这种方式完成吗?

ios - 发送大尺寸图像、视频和音频时 XMPP 客户端断开连接

ios - 无法安装 Xcode 7 beta 5 的 iOS 模拟器

ios - Swift - 本地通知不会被触发

ios - 从子 CollectionViewCell 访问父 tableViewCell

ios - 如何使用 AFNetworking 永久保存 cookie,直到应用程序从 iPhone 中删除?