【发布时间】:2015-12-22 09:30:38
【问题描述】:
我对 swift 还很陌生,并且一直在操场上玩 NSNotificationCenter。我收到了错误:
执行被中断,原因:signal SIGABRT
使用postNotificationName 函数时。我无法弄清楚问题发生的确切原因,任何指针都会有所帮助!
let notificationKey = "rachel"
class FirstViewController {
var sentNotificationLabel = "Nothing has been sent yet."
func addObserver() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateNotificationLabel", name: notificationKey, object: nil)
}
func notify() {
NSNotificationCenter.defaultCenter().postNotificationName(notificationKey, object: self)
}
func updateNotificationLabel() {
self.sentNotificationLabel = "Notification sent!"
}
}
class SecondViewController {
var notificationLabel = "I have not been notified yet."
func addObserver() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateNotificationLabel", name: notificationKey, object: nil)
}
func updateNotificationLabel() {
self.notificationLabel = "I've been notified!"
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
class ThirdViewController {
var notificationLabel = "I have not been notified yet."
func addObserver() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateNotificationLabel", name: notificationKey, object: nil)
}
func updateNotificationLabel() {
self.notificationLabel = "I've been notified too!"
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
var firstView = FirstViewController()
print(firstView.sentNotificationLabel) // Nothing has been sent yet.
firstView.addObserver()
firstView.updateNotificationLabel()
firstView.notify() // ERROR 'Execution was interrupted, reason: signal SIGABRT'
print(firstView.sentNotificationLabel) // Notification sent!
var secondView = SecondViewController()
print(secondView.notificationLabel)
var thirdView = ThirdViewController()
print(thirdView.notificationLabel)
【问题讨论】:
-
如果
notify()通过你的通知调用updateNotificationLabel(),你为什么要在firstView.notify()之前调用firstView.updateNotificationLabel()?
标签: swift nsnotificationcenter