使用NSNotificationCenter在View Controllers之间传递数据

时间:2015-12-14 23:39:03

标签: ios swift nsnotificationcenter nsnotification

大家。我写了这段代码来在VC之间传递数据,但我不确定它为什么不起作用。

这是ViewController1中的代码: -

import UIKit
import Foundation

let foodDict: [String:String] = [
    "Orange": "Fruit",
    "Carrot": "Vegetable",
    "Pear": "Fruit",
    "Spinach": "Vegetable"
]

class ViewController1: UIViewController {

     override func viewDidLoad() {
         super.viewDidLoad()

         NSNotificationCenter.defaultCenter().postNotificationName("SEND_STRING", object: nil, userInfo: foodDict)

     }
 }

在ViewController2中: -

import UIKit
import Foundation

class ViewController2: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "printStringDict:", name: "SEND_STRING", object: nil)
    }

    func printStringDict(notification: NSNotification) {

        print("Got the notification...")
        let foodDictFromVC1 = notification.userInfo as! [String:String]
        print(foodDictFromVC1)
    }

}

VC2没有得到字典(因为没有打印)。有人可以帮忙吗?提前谢谢。

2 个答案:

答案 0 :(得分:1)

所以问题是你发布了通知但你的VC2还没有初始化,所以没有人可以得到你在视图中加载VC1的帖子。最好使用prepareForSegue(segue:UIStoryboardSegue,sender:AnyObject?)函数在两个与segue连接的ViewController之间进行通信,例如:

import UIKit
import Foundation



class ViewController1: UIViewController {

    let foodDict: [String:String] = [
        "Orange": "Fruit",
        "Carrot": "Vegetable",
        "Pear": "Fruit",
        "Spinach": "Vegetable"
    ]
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "segueIdentifierSetInStoryboard" {
            if let destinationVC = segue.destinationViewController as? ViewController2{
                destinationVC.printStringDict(foodDict)
            }
        }
    }
}

class ViewController2: UIViewController {       
    func printStringDict(fooDict:[String:String]) {
        print(fooDict)
    }
}

答案 1 :(得分:0)

如果我明白: ViewController1 - > ViewController2

在这种情况下,您的代码将无法正常工作,因为在ViewController1中您发布了通知,但没有任何内容正在监听您的通知,因为ViewController2尚未创建!

在ViewController2中,添加一个观察者,该观察者收听任何符合名称" SEND_STRING"的通知。要使通知有效,您必须在ViewController1上添加一个观察者,然后在ViewController2上触发发布通知! => ViewController1将会收到通知!