gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:05:43 25 4
gpt4 key购买 nike

我有一个包含大约 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com