如何在没有 segue 的情况下使用通知中心将数据从第一个 TableView 发送到第二个 TableView

How can I send data from FirstTableView to SecondTableView using Notification Center without segue

当我尝试使用 NotificationCenter 设计模式将数组从 UITableView 传递到另一个数组时遇到问题(因为我在这 2 个 UIViewController 之间没有 segue)。我不知道我做错了什么,但我在第二个视图控制器中没有收到任何数据。

我的函数如下所示:

* 首先 VC - 发送者控制器(从我发送数据的地方)*

class ProductsViewController: UIViewController{

var selectedProductsArray = [Product]()

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)


        // Implement Notification Design Pattern to send data
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "productsToLoad"), object: selectedProductsArray)

        print(selectedProductsArray) // Here I have some data in this array (Photo here: https://ibb.co/k8hoEy)
    }

* 第二个 ViewController - 接收器控制器(我将在其中接收数据)*

class CartViewController: UIViewController {

var productsInCartArray = [Product]()

 // We retrieve data from "selectedProductsArray" and we append all the products into "productsInCartArray"
    @objc func notificationRecevied(notification: Notification) {
        productsInCartArray = notification.object as! [Product]
        print(productsInCartArray)
    }

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // Add observer to watch when something was changed in "selectedProductsArray"
        NotificationCenter.default.addObserver(self, selector: #selector(notificationRecevied(notification:)), name: NSNotification.Name(rawValue: "productsToLoad"), object: nil)

       print(productsInCartArray) // Output: []

    }

override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        // We remove the observer from the memory
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "productsToLoad"), object: nil)
    }

}

截图:

感谢您抽空阅读本文!

您需要从 CartViewController

viewWillDisappear 中删除它
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "productsToLoad"), object: nil)

当您 post 在产品中时,卡片不会显示,因此里面没有侦听器,除此之外 CartViewController 应该在您 post 任何数据之前至少打开一次来自 ProductsViewController

//

您可以完全删除 NotificationCenter 的工作,并在 CartViewController

中执行此操作
let products = ((self.tabBarController?.viewControllers![0] as! UINavigationController).topViewController as! ProductsViewController).selectedProductsArray 

Note : 不用担心 ! 展开它不会崩溃