2017-07-28 145 views
0

收到此錯誤NSInternalInconsistencyException觀察者contentSize

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) 

    } 
} 

代碼奇怪的是,我試圖消除所有這些代碼,但我仍然得到了同樣的錯誤,是什麼!!

回答

0

檢查標誌,如果你awakeFromnib方法中不添加觀察者然後將其添加相應: -

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

沒有工作,仍然會崩潰,正如我所說的,如果我刪除所有觀察者關鍵的事情,但它仍然崩潰。這很奇怪 – TestDjay