ios - 大型 uitableview(1000 行)在 reloadData() 上卡住

标签 ios swift uitableview

我有一个包含大约 1000 行的 UITableView。我还有一个每 6 秒运行一次的计时器,用于从 Web 服务获取数据。每次我调用 reloadData() 时都会出现一个问题——我的应用程序会在很短的时间内非常明显地卡住。这在滚动时非常明显。 我尝试只获取大约 400 行,然后 blip 消失了。有什么技巧可以在仍然获取 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()
      }
   }
}

UITableViewData源码:

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 更新 TableView ,这意味着在更新数组时 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/

相关文章:

ios - 从字符串创建 double

swift - 私有(private)变量可以从类外访问

ios - 我遇到这样的错误,我想到了 tableView,但我在堆栈跟踪中看到了有关 FBSDK 的信息

iphone - sqlite 只返回一条记录

ios - iPhone - 从另一个 View Controller 调用函数

uitableview - 如何实现 TableView.insertRows

ios - UIButton 在 UITableview 中不起作用

ios - 如何解决 uitableviewcell 重用的自定义子类的问题?

php - 如何正确地将图片加载到 UITableVIew 中

swift - 带数组的实用程序类