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

问题描述 投票:0回答:3

现在和我得到这个错误,而试图注册一个观察者林学习的通知中心:Cannot convert value of type 'Selector' to expected argument type 'String'

我观察代码:

NotificationCenter.addObserver(self, forKeyPath: #selector(receivedMsg), options: Notification.Name("NC1"), context: nil)

功能receivedMsg:

 @objc func receivedMsg() {
print("MSG Received")
}

工作关​​本教程:https://www.hackingwithswift.com/example-code/system/how-to-post-messages-using-notificationcenter

为什么会出现这个错误,我能做些什么来解决这个问题? (SWIFT 4.2)

ios swift4.2 notificationcenter
3个回答
0
投票

你需要解决两件事情:

  1. NotificationCenter访问NotificationCenter.default的实例
  2. 使用上addObserver可用NotificationCenter方法签名

完整的代码应该是这样的

NotificationCenter.default.addObserver(self, selector: #selector(receivedMsg), name: Notification.Name("NC1"), object: nil)

0
投票

您正在使用错误的方法来添加为一个观察者。你想使用它代替:NotificationCenter.default.addObserver(self, selector: #selector(receivedMsg), name: Notification.Name("NS1"), object: nil)


0
投票
NotificationCenter.default.addObserver(self, selector: #selector(receivedMsg), name: Notification.Name("NC1"), object: nil)

然后实现

@objc func receivedMsg() {
    print("MSG Received")
}

的keyPath用于志愿通知

韩国国际志愿者组织和通知中心之间最大的区别是,志愿追踪到的对象的具体变化,而通知中心是用来跟踪一般事件,当按钮被按下后的动作等。

可能会在此link细节

© www.soinside.com 2019 - 2024. All rights reserved.