ios - 完成解析功能后重新加载TableView中的数据
问题描述
我正在尝试在功能完成后重新加载数据:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let presentingVC = presentingViewController as? DealsViewController {
//checks if presenting VC's city is the same as original, doesn't run if it is
if presentingVC.city != self.currentCity {
DispatchQueue.main.async {
//reloads the data but before completion of the below function "getDealInfo"
presentingVC.DealsTableView.reloadData()
presentingVC.DealsTableView.layoutIfNeeded()
}
}
//checks if presenting VC's city is the same as original, doesn't run if it is
if presentingVC.city != self.currentCity {
presentingVC.city = self.currentCity
presentingVC.deleteAllDeals()
//this is the function that gets called
presentingVC.getDealInfo()
presentingVC.cityOutlet.setTitle(self.currentCity,for: .normal)
}
}
tableView.deselectRow(at: indexPath, animated: true)
searching = false
self.dismiss(animated: true, completion: nil)
searchBar.resignFirstResponder()
}
如您所见,在返回到先前的视图控制器以获取提供的新信息后,我调用了 reload 函数。但是,表格视图会在接收新值之前更新。结果,我的 tableView 是空的,但是我的值存储在我的数组中。
getDealInfo 是异步的:
func getDealInfo() {
let query = PFQuery(className: "Deal")
query.whereKey("City", equalTo: city)
query.order(byDescending: "Priority")
query.findObjectsInBackground(block: { (objects: [PFObject]?,error:
Error?) in
if let objects = objects {
for object in objects {
self.dealsArray.append(object["Deal"] as! String)
}
}
}
})
}
解决方案
添加一个完成处理程序getDealInfo
,以便在完成时收到通知:
func getDealInfo(_ completionHandler: @escaping () -> Void) {
//Do async work
completionHandler()
}
然后在调用代码中:
presentingVC.getDealInfo {
self.presentingVC.DealsTableView.reloadData()
}
如果未在主线程中调用完成处理程序,那么您希望DispatchQueue.main.async
像当前正在使用的那样使用,以便reloadData
在主线程中完成调用。
推荐阅读
- python - PyYAML 在不同的操作系统中表现不同
- apache-kafka - Spring Kafka - 消费者、容器和监听器
- windows - Word VBA - 表合并问题
- node.js - 在 src中定义的图像未显示在我的 heroku 应用程序上
- hyperledger-explorer - 启动超级账本资源管理器失败
- exact-online - itgendch033:后备数据库需要 Invantive Data Replicator 将“ExactOnlineXML.XML.SubscriptionLines”的列数限制为 1,000
- postgresql - 如何使用 PSQL 运行和自动创建数据库
- php - PHP 正则表达式接受日语和英语语言
- python - 在 pandas DataFrame 的每一列中查找第一个非零值
- javascript - MomentJS - 显示现在/明天而不是今天/明天的日期