首页 > 解决方案 > 如何在没有 segue 的情况下使用通知中心将数据从 FirstTableView 发送到 SecondTableView

问题描述

当我尝试使用 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)
    }

}

截屏: 在此处输入图像描述

如果您正在阅读本文,感谢您抽出宝贵时间!

标签: iosswiftnsarraynsnotificationcenter

解决方案


viewWillDisappear您需要从CartViewController

NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "productsToLoad"), object: nil)

因为当您在产品中发布时,卡片没有显示,所以里面没有监听器,除此之外,CartViewController在您发布任何数据之前,应该至少打开一次ProductsViewController

//

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

let products = ((self.tabBarController?.viewControllers![0] as! UINavigationController).topViewController as! ProductsViewController).selectedProductsArray 

Note :不要担心!打开它不会崩溃


推荐阅读