首页 > 解决方案 > 完成解析功能后重新加载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)
              }
            }
       }
    })
 }

标签: iosswiftuitableviewparse-platformreload

解决方案


添加一个完成处理程序getDealInfo,以便在完成时收到通知:

func getDealInfo(_ completionHandler: @escaping () -> Void) {
    //Do async work
    completionHandler()
}

然后在调用代码中:

presentingVC.getDealInfo {
    self.presentingVC.DealsTableView.reloadData()
}

如果未在主线程中调用完成处理程序,那么您希望DispatchQueue.main.async像当前​​正在使用的那样使用,以便reloadData在主线程中完成调用。


推荐阅读