Search code examples
iosswiftnsarraynsnotificationcenter

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


I have a problem when I try to pass an array from a UITableView to another one using NotificationCenter Design Pattern (because I don't have a segue between this 2 UIViewControllers). I don't know what I'm doing wrong but I don't receive any data in my second view controller.

My functions looks like this:

* First VC - The Sender Controller (From where I send data) *

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)
    }

* Second ViewController - The Receiver Controller (Where I will receive the data) *

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)
    }

}

Screenshot: enter image description here

Thank you for your time if you are reading this !


Solution

  • You need to remove this from viewWillDisappear of CartViewController

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

    as when you post in products the cards are not shown so there is no listener inside it , beside that CartViewController should be opened at least once before you post any data from ProductsViewController

    //

    you can completely remove the NotificationCenter work , and do this in CartViewController

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

    Note : Don't worry for ! unwrapping it won't crash