Как я могу отправить данные из FirstTableView в SecondTableView с помощью Центра уведомлений без перехода - PullRequest
0 голосов
/ 30 июня 2018

У меня проблема, когда я пытаюсь передать массив из UITableView в другой, используя шаблон проектирования NotificationCenter (потому что у меня нет перехода между этими 2 UIViewControllers). Я не знаю, что я делаю неправильно, но я не получаю никаких данных в моем втором контроллере представления.

Мои функции выглядят так:

* Первый 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)
    }

}

Скриншот: enter image description here

Спасибо за ваше время, если вы читаете это!

1 Ответ

0 голосов
/ 30 июня 2018

Вы должны удалить это из 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 : Не беспокойтесь за ! разворачивание не приведет к краху

...