使用 NSNotificationCenter 在视图控制器之间传递数据

Passing data between View Controllers with NSNotificationCenter

各位。我编写这段代码是为了在 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 没有得到字典(因为没有打印)。有人可以帮忙吗?提前致谢。

所以问题是你 post 通知但是你的 VC2 还没有初始化所以没有人能得到你看到的这个 post 在 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)
    }
}

如果我理解: ViewController1 -> ViewController2

在那种情况下,您的代码将永远无法工作,因为在 ViewController1 中您 post 收到通知,但没有任何内容正在监听您的通知,因为 ViewController2 尚未创建!

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