应用在 textview.becomeFirstResponder 崩溃

App crashed at textview.becomeFirstResponder

我的应用有时会在调用 textView.becomeFirstResponder() 时崩溃。抛出的错误很奇怪:

-[UITextSelectionView keyboardShownWithNotif:]: unrecognized selector sent to instance 0x16899070

有时是:

-[UIImageView keyboardShownWithNotif:]: unrecognized selector sent to instance 0x178e2610

我确实添加了通知侦听器:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardShown(notif:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardHidden), name: .UIKeyboardWillHide, object: nil)

但是观察者是我定义的自定义视图,为什么系统会向UITextSelectionViewUIImageView发送通知?

在 iOS 8.4.1 中找到,在 iOS 9.

中未转载

这里发生了什么?

seems like you added an notif. observer to show/hide keyboard. 
Try to remove observer in dealloc method

 - (void) dealloc {
       [[NSNotificationCenter defaultCenter] removeObserver:self]; //Or whichever observer you want to remove
}

在swift 3:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
            NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window)
            NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window)
}

deinit {
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window)
}