我正在学习通知中心,并在尝试注册观察者时遇到此错误:
Cannot convert value of type 'Selector' to expected argument type 'String'
我的观察者代码:
NotificationCenter.addObserver(self, forKeyPath: #selector(receivedMsg), options: Notification.Name("NC1"), context: nil)
功能接收消息:
@objc func receivedMsg() {
print("MSG Received")
}
正在研究本教程:https://www.hackingwithswift.com/example-code/system/how-to-post-messages-using-notificationcenter
为什么会出现此错误,我该如何解决? (快速4.2)
答案 0 :(得分:0)
您使用错误的方法添加为观察者。您想改用这个:
NotificationCenter.default.addObserver(self, selector: #selector(receivedMsg), name: Notification.Name("NS1"), object: nil)
答案 1 :(得分:0)
您需要修复两件事:
使用NotificationCenter
NotificationCenter.default
的实例
使用addObserver
上的NotificationCenter
方法签名
完整代码应类似于
NotificationCenter.default.addObserver(self, selector: #selector(receivedMsg), name: Notification.Name("NC1"), object: nil)
答案 2 :(得分:0)
NotificationCenter.default.addObserver(self, selector: #selector(receivedMsg), name: Notification.Name("NC1"), object: nil)
然后实施
@objc func receivedMsg() {
print("MSG Received")
}
Keypath用于KVO通知
KVO和NotificationCenter之间的最大区别是KVO跟踪对象的特定更改,而NotificationCenter用于跟踪一般事件,例如按下按钮以发布操作时。
可能会在此link
中获取详细信息