【问题标题】:NSNotification.Name.UIKeyboardWillShow crash - Unable to find causeNSNotification.Name.UIKeyboardWillShow 崩溃 - 无法找到原因
【发布时间】:2018-01-27 17:58:47
【问题描述】:

我的应用程序的用户报告了随机崩溃。我已经集成了 CrashAnalytics,它提供了以下详细信息:

__CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 20. 

表示的行号是154,即:

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). 

以下是我编写的代码,其中包含这一行:

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)
    }

首先,这是非常随机的,我从来没有得到它。其次,我无法找到它的确切原因。这是因为通知观察者还是因为 notesView(不是 nil)。
正如here 建议的那样,我应该在 deinit 中删除键盘通知观察器吗?
如果有人以前遇到过这种情况,请指导我。

【问题讨论】:

  • 通知选择器的正确 Swift 3 和 ObjC 兼容语法是 func keyboardShown(_ notification: Notification)- 注意下划线。
  • @vadian :这真的重要吗?
  • 更新 DispatchQueue.main.async {notesView.content...} 中的 noteview 框架

标签: ios swift nsnotificationcenter crashlytics


【解决方案1】:

把你的函数签名改成这个

@objc func keyboardShown(_ notification: Notification)

【讨论】:

  • 知道为什么@objc 有效吗?我面临类似的崩溃,但无法重现。谢谢。
  • 您能解释一下为什么在函数中添加@objc 有效吗?
  • 原因是从swift 3升级到swift 4需要@objc作为选择器
  • 拯救了我的夜晚 :)
猜你喜欢
  • 2012-12-26
  • 2020-12-15
  • 1970-01-01
  • 2014-11-13
  • 1970-01-01
  • 1970-01-01
  • 2016-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多