gpt4 book ai didi

swift - NotificationCenter 观察员没有收到帖子

转载 作者:搜寻专家 更新时间:2023-11-01 06:04:39 25 4
gpt4 key购买 nike

我已经尝试了好几个小时让观察员收到通知帖子,但每次尝试都失败了。我将观察者放入我的 Root View Controller 中,它是一个嵌入式选项卡 Controller ,并试图让其中一个选项卡 Controller 发送一个帖子供其接收,但无济于事。我这辈子都弄不明白,但我真的很想弄明白,因为通知可能非常有用!

这是我的代码:

View Controller

let myNotification = Notification.Name(rawValue:"categoryChange")

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

override func viewDidLoad() {
super.viewDidLoad()
let nc = NotificationCenter.default
nc.addObserver(forName:myNotification, object:"test", queue:nil, using:test)
}

func test(notification:Notification) -> Void {
print("Yo")
}

这是我的DashboardController:

override func viewDidLoad() {
super.viewDidLoad()
let myNotification = Notification.Name(rawValue:"categoryChange")
let nc = NotificationCenter.default
nc.post(name:myNotification,
object: nil,
userInfo:["message":"Hello there!"])
}

我尝试将观察者放入 init、viewDidLoadviewDidAppear 而帖子位于 viewDidLoad 中,我做了反之亦然。到目前为止没有任何效果,我也不知道为什么。

在此先感谢任何可以提供帮助的人!

最佳答案

您的问题是当您在 NotificationCenter 中添加观察者时,您正在通过 object 参数传递 test(作为 String) >.

(来自文档)对象:

The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer.

If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to deliver it to the observer.

这就是你的通知没有被调用的原因,因为你没有在 object 的帮助下发布通知,只需将 object 设置为 nil 将为您工作。

nc.addObserver(forName:myNotification, object:nil, queue:nil, using:test)

关于swift - NotificationCenter 观察员没有收到帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40929840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com