分段故障:11; (xcode 8,Swift 3)使用NotificationCenter后

Dee*_*put 3 ios notificationcenter swift3 xcode8

在Xcode 8中获取分段错误

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

由于信号命令失败:分段错误: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
}
Run Code Online (Sandbox Code Playgroud)

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

OOP*_*Per 5

主题:分段错误:11,这是Xcode8/Swift3的一个错误,你应该发送错误报告.

关于你的代码:

NotificationCenter.default.removeObserver(NSNotification.Name.UIKeyboardWillShow)
NotificationCenter.default.removeObserver(NSNotification.Name.UIKeyboardWillHide)
Run Code Online (Sandbox Code Playgroud)

没有方法删除只指定其名称的观察者.您需要为其指定observer对象removeObserver(_:).

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

NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
Run Code Online (Sandbox Code Playgroud)

我相信这不会让你的Xcode崩溃.