ios - 如何在没有 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)
}
}
如果您正在阅读本文,感谢您抽出宝贵时间!
解决方案
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 :
不要担心!
打开它不会崩溃
推荐阅读
- mongodb - 如何将模型从文档列表更新为mongodb中的数组
- postgresql - 从数据工厂读取 Postgress(以 SQL_ASCII 编码)
- cookies - 如何在我的扩展程序中获取带有凭据的 URL,而不会将 cookie 泄漏到用户 cookie 存储?
- python-3.x - 如何将数据附加到for循环中的空列表?
- methods - 在输入中输入数据
- sql - django get_next_by_FOO() 查询是如何工作的?
- android - WebView 显示消息“抱歉有错误”
- ubuntu - 如何使用 SNMP Ubuntu 获取有关已安装程序的信息
- r - 如何按日期获取滞后变量的差异?
- angular - Angular JWT:授权标头为空?