0

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

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”是否被调用,因为我添加了打印语句来检查这一点。

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

4

1 回答 1

0

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

这意味着您必须在发布任何通知之前注册观察员。如果您在此之前发布任何内容,NSNotificationCenter则会查看观察者name并看到没有人在听它,因此不会发生任何事情。

于 2020-09-24T01:23:36.350 回答