我有一个大约1000行的视图。我还有一个计时器,每6秒运行一次,从web服务获取数据。每次我调用reloadData()时,都会有一个短暂的闪现——我的应用程序会明显冻结一小会儿。这在滚动时非常明显。
我试着只取了大约400行数据,结果这个点消失了。有什么技巧可以在获取1000行数据的同时消除这个问题吗?

var items: [Item] = []

Timer.scheduledTimer(withTimeInterval: 6, repeats: true) { [weak self] _ in
   guard let strongSelf = self else { return }

   Alamofire.request(urlString, method: method, parameters: params) { response in
      // parse the response here and save it in array called itemsFromResponse
      OperationQueue.main.addOperation {
         strongSelf.items = itemsFromResponse
         strongSelf.itemsTableView.reloadData()
      }
   }
}

UITableViewDataSource代码:
extension ItemViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "itemCell", for: indexPath)

        cell.textLabel?.text = items[indexPath.row].name

        return cell
    }
}

最佳答案

导致此问题的原因是,您正在存储响应中的项,然后从同一个OperationQueue更新表视图,这意味着在更新阵列时正在阻止UI线程。如果您不需要对任务进行精细的控制(例如取消和高级调度,就像您不需要这里一样),那么使用操作队列本身并不是调度任务的最佳方式。您应该使用DispatchQueuesee here for more
为了解决问题,应该从后台完成处理程序更新数组,然后更新表。

Timer.scheduledTimer(withTimeInterval: 6, repeats: true) { [weak self] _ in
   guard let strongSelf = self else { return }

   Alamofire.request(urlString, method: method, parameters: params) { response in
      // parse the response here and save it in array called itemsFromResponse
      strongSelf.items = itemsFromResponse
      // update the table on the main (UI) thread
      DispatchQueue.main.async {
         strongSelf.itemsTableView.reloadData()
      }
   }
}

您还应该寻找一种更有效的方法来获取新数据,因为每6秒重新加载一次整个数据集对于用户手机上的数据或CPU来说不是很有效。

关于ios - 较大的uitableview(1000行)在reloadData()上卡住,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45192855/

10-11 15:02