当我尝试使用NotificationCenter设计模式将数组从UITableView传递到另一个数组时遇到问题(因为在这2个UIViewController之间没有关系)。我不知道自己在做什么错,但是我的第二个视图控制器没有收到任何数据。
我的功能如下:
*第一个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)
}
}
如果您正在阅读本文,谢谢您的时间!
答案 0 :(得分:1)
您需要将其从viewWillDisappear
的{{1}}中删除
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 :
展开不会崩溃