问题
Users of my app have reported a random crash. I have integrated CrashAnalytics which is giving the following details :
__CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 20.
The line number indicated is 154, which is :
self.notesView.content.frame = CGRect(x: self.notesView.content.frame.origin.x, y: self.notesView.content.frame.origin.y, width: self.notesView.content.frame.size.width, height: self.notesView.content.frame.size.height - keyboardFrame.size.height).
Following is the code I have written which consist of this line :
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
label_title.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardShown), name:NSNotification.Name.UIKeyboardWillShow, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(keyboardHide), name:NSNotification.Name.UIKeyboardWillHide, object: nil);
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
label_title.removeObserver(self, forKeyPath: "contentSize")
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func keyboardShown(notification: NSNotification) {
let info = notification.userInfo!
let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
self.notesView.content.frame = CGRect(x: self.notesView.content.frame.origin.x, y: self.notesView.content.frame.origin.y, width: self.notesView.content.frame.size.width, height: self.notesView.content.frame.size.height - keyboardFrame.size.height)
}
Firstly, this is quite random and I never get it. Secondly, I am not able to find exact cause for it. Is this because of notification observer or because of notesView (which is not nil).
As suggested here, should I remove keyboard notification observer in deinit ?
Please guide me through this if someone has experienced this previously.
回答1:
Change signature of your function to this
@objc func keyboardShown(_ notification: Notification)
来源:https://stackoverflow.com/questions/48478802/nsnotification-name-uikeyboardwillshow-crash-unable-to-find-cause