将数据间接传递给不相关的 NSViewController

Passing Data Indirectly to an Unrelated NSViewController

在 MakeEntry 视图控制器中:

 notifDictionary = ["carryData": carrierArray]

        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "dataCarrier") , object: nil, userInfo: notifDictionary)

在 EntryList 视图控制器中: (尝试一次使用两种类型的选择器方法,甚至一起使用它们,但都没有运气!请帮忙!) 变量 datumDictdatumArray 以及 carrierArraynotifDictionary[ 的复制接收器。 =77=]

var datumDict: [String:[String]] = [:]
var datumArray: [String] = []


override func viewDidLoad() {
    super.viewDidLoad()



    NotificationCenter.default.addObserver(self, selector: #selector(self.getThatDict(_:)), name: NSNotification.Name(rawValue: "dataCarrier") , object: nil)

    NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "dataCarrier") , object: nil, queue: nil, using: catchNotification)

    //datumArray = datumDict["carryData"]!

}




 @objc func onNotification(notification:Notification)
    {
        print(notification.userInfo!)
    }

func catchNotification(notification: Notification) -> Void
{
    let theDict = notification.object as! NSDictionary
    datumDict = theDict as! [String: [String]]
    guard let theData = notification.userInfo!["carryData"] as? [String:[String]] else { return }
    datumDict = theData
}


@objc func getThatDict(_ notification: NSNotification)
{
    print(notification.userInfo ?? "")
    if let dict = notification.userInfo as NSDictionary?
    {
        if let thatDict = dict["carryData"] as? [String: [String]]
        {
            datumDict = thatDict
        }
    }
}

需要注意的是 "globals and singletons should be avoided," 听起来它们非常适合您的尝试。当您对 Cocoa 越来越熟悉时,您可以采用更复杂的方法来完成此操作(依赖注入)。当您对 Cocoa.

越来越熟悉时,请查看此内容

创建一个简单的单例类型:

// AppState.swift

class AppState {
    // Basic singleton setup:
    static let shared = AppState()
    private init() {} // private prevents instantiating it elsewhere

    // Shared state:
    var carrierArray: [String] = []
}

从您的视图控制器访问它:

// YourViewController.swift:

    @IBAction func doSomething(_ sender: Any) {
        AppState.shared.carrierArray = ...
    }

如果您需要在共享状态更改时更新其他视图控制器,通知是一个很好的工具。您可以在 carrierArray 上使用 didSet 来执行此操作,或者只需手动触发通知。