【问题标题】:NSNotification sent data is blank after page is loaded页面加载后 NSNotification 发送的数据为空
【发布时间】:2015-10-06 22:17:23
【问题描述】:

我通过 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)
}

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

任何帮助将不胜感激。谢谢

【问题讨论】:

  • 你为什么使用 NSNotification 而不仅仅是通过 ViewControllers 中的变量传递数据?
  • 我有静态表格单元格
  • 为什么将数据存储在视图控制器而不是数据模型中。无论如何,age 是如何声明的,何时何地。
  • 赞夫赞。而且我不明白为什么即使你有静态单元格也不能用变量传递数据,它们之间没有关系......
  • 在ViewController 3中声明var age: AnyObject = ""

标签: ios iphone swift uiviewcontroller notifications


【解决方案1】:

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

话虽如此,从您的代码看来,您在发送通知时误解了object 参数。 object 只是限制通知的范围。如果您想传递数据,您必须创建一个新的NSNotification 并包含一个userInfo 字典,其中包含您希望接收器获取的任何数据。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 2015-11-17
    相关资源
    最近更新 更多