ios - 段错误 : 11; (xcode 8, Swift 3) 使用 NotificationCenter 后

标签 ios swift3 xcode8 notificationcenter

在 Xcode 8 中获取段错误

我最近将我的项目迁移到了 Swift 3。 Xcode 版本 8.0 (8A218a) 每当我使用 UIKeyboardWillShow 通知时,我都会收到此错误:

Command failed due to signal: Segmentation fault: 11`

这就是我在代码中使用通知的方式:

override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(NSNotification.Name.UIKeyboardWillShow)
    NotificationCenter.default.removeObserver(NSNotification.Name.UIKeyboardWillHide)
    NotificationCenter.default.addObserver(self, selector: #selector(myViewController.keyboardWillShow(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(myViewController.keyboardWillHide(_:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil)

}


func keyboardWillShow(_ sender: Notification) {
     //keyboardWillShow Method
}

func keyboardWillHide(_ sender: Notification) {
    // keyboardWillHide Method
}

当我注释掉 viewWillAppear 方法中的代码时,项目成功运行。

最佳答案

主题:Segmentation fault: 11,这是Xcode8/Swift3的bug,你应该发一个bug report .

关于您的代码:

NotificationCenter.default.removeObserver(NSNotification.Name.UIKeyboardWillShow)
NotificationCenter.default.removeObserver(NSNotification.Name.UIKeyboardWillHide)

没有删除观察者的方法只指定他们的名字。您需要为 removeObserver(_:) 指定观察者对象。

我不确定这是你想要的,但你可以使用 removeObserver(_:name:object:) 方法,如下所示:

NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)

我相信这不会让您的 Xcode 崩溃。

关于ios - 段错误 : 11; (xcode 8, Swift 3) 使用 NotificationCenter 后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39426535/

相关文章:

iOS 写入 CSV 文件 : which encoding to use

iphone - 使用自定义搜索文本字段过滤 tableView

ios - XMPP 与服务器连接并在 iOS 中配置客户端

ios - 如何获取以前日期的 HealthKit 总步数

swift - 如何压制 "result not used"警告

firebase - 错误: Could not build Objective-C module 'Firebase'

iOS - 创建一个依赖于标准框架的静态库

ios - 删除单元格后使用自定义布局调整 UICollectionView 的大小

ios - 如何修复 swift 3 中的 "missing argument label in call"

swift - 转换到 Swift 3 的困难