加载页面后,NSNotification发送的数据为空白



我通过NSNotification将数据从ViewController 1发送到ViewController 3,从ViewController 2发送到ViewController 3。

NSNotificationCenter.defaultCenter().postNotificationName("retirementChange", object: retirementText?.text)

当我将NSNotification中的数据设置为ViewController 3中的一个变量时,我打印来自ViewController 3的数据。我将变量age设置为通知对象。

NSNotificationCenter.defaultCenter().addObserver(self, selector: "setRetirementAge:", name: "retirementChange", object: nil)
func setRetirementAge(notification: NSNotification){
    age = notification.object!
    print(age)
}

当时在控制台中打印得很好,但是当我尝试使用页面加载后的值age时,它是空白的。

任何帮助将非常感激。由于

您应该考虑到您的问题的评论中提到的内容,也许不使用NSNotification,而是以有序的方式将数据传递给控制器。通知实际上是用来通知屏幕上的控制器当其他地方发生变化时,通常是在后台线程上。正确的方法是在视图控制器出现之前设置显示正确的数据。它应该通过一些可用的数据模型来设置,或者通过由呈现视图控制器在通常的方法中设置的变量来设置,例如prepareForSegue

话虽这么说,似乎从你的代码,你误解了object参数时发送通知。object只是限制通知的范围。如果你想传递数据,你必须创建一个新的NSNotification,并包含一个userInfo字典,其中包含你想要接收者获得的任何数据。

let notif = NSNotification(name: "retirementChange", object: nil, userInfo: ["age": 42])
NSNotificationCenter.defaultCenter().postNotification(notif)

最新更新