NSInternalInconsistencyException观察者contentSize

时间:2017-07-28 14:51:56

标签: swift uitextview

获取此错误

2017-07-28 20:17:34.636 App[78013:1799389] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'An instance 0x7fa97b0bf400 of class App.MessagesCellTextView was deallocated while key value observers were still registered with it. Current observation info: <NSKeyValueObservationInfo 0x618000434e80> (
<NSKeyValueObservance 0x618000243c60: Observer: 0x7fa97b0bf400, Key path: contentSize, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x618000243c90>

当我离开聊天控制器并返回时。

这是我的contentSize代码

var observerAdded: Bool = false

override func awakeFromNib() {
    super.awakeFromNib()

    self.addObserver(self, forKeyPath:"contentSize", options:.new, context:nil)
    observerAdded = true



}

deinit {
    if (observerAdded) {
        observerAdded = false
        self.removeObserver(self, forKeyPath: "contentSize")
    }
}


override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if let textView = object as? UITextView {

        var y: CGFloat = (textView.bounds.size.height - textView.contentSize.height * textView.zoomScale) / 2.0
        y = (y < 0.0 ? 0.0 : y)

        textView.contentOffset = CGPoint(x: 0, y: -y)

    }
}
奇怪的是,我试图删除所有这些代码,但我仍然得到相同的错误,什么!!

1 个答案:

答案 0 :(得分:0)

如果未在awakeFromnib方法中添加观察者,请检查标记然后相应地添加: -

override func awakeFromNib() {
    super.awakeFromNib()
   if !observerAdded {
     self.addObserver(self, forKeyPath:"contentSize", options:.new, context:nil)
     observerAdded = true
  }
}