通知中心-无法将类型“选择器”的值转换为预期的参数类型“字符串”

时间:2019-02-07 03:39:11

标签: ios swift4.2 notificationcenter

我正在学习通知中心,并在尝试注册观察者时遇到此错误: 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)

3 个答案:

答案 0 :(得分:0)

您使用错误的方法添加为观察者。您想改用这个: NotificationCenter.default.addObserver(self, selector: #selector(receivedMsg), name: Notification.Name("NS1"), object: nil)

答案 1 :(得分:0)

您需要修复两件事:

  1. 使用NotificationCenter

  2. 访问NotificationCenter.default的实例
  3. 使用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

中获取详细信息