添加观察者时未输入选择器功能

Selector function not being entered when observer is added

在我的第一个视图控制器中,我 post 使用以下代码的通知:

NotificationCenter.default.post(name: Notification.Name("date"), object: formattedDate)

然后我使用以下代码在第二个视图控制器中“接收”通知:

func receiveNotification () {
    NotificationCenter.default.addObserver(self, selector: #selector(self.didGetTheDate(_:)), name: NSNotification.Name("date"), object: nil)
}

@objc 
func didGetTheDate(_ notification: Notification) {
    print("In did get date")
    date = notification.object as! String    
}

但是,函数“didGetTheDate”从未被调用过。 我已经三次检查函数“receiveNotification”是否被调用,因为我添加了打印语句来检查它。

有人可以帮我解决这个问题吗?

NSNotificacionCenter是观察者模式的一种变体,你可以阅读here

这意味着您必须在 post 发送任何通知之前注册观察员。如果您在此之前 post 进行任何操作,NSNotificationCenter 将查看 name 的观察者,并且会发现没有人在监听它,因此什么也不会发生。