[英]UITableView scrolling performance problem
我目前是一名 5 個月的初級 ios 開發人員。
我正在進行的項目是一個應用程序,它通過 websocket 連接實時顯示 70 種加密貨幣的價格。
我們在開發應用程序時使用了 websocket 連接、UItableview、UITableViewDiffableDataSource、NSDiffableDataSourceSnapshot。
但是現在在tableview中滾動時會出現滾動速度變慢或不停止滾動和UI鎖定等問題,因為同時處理的數據太多。
在我使用計時器分析器檢查 CPU 性能后,我得出的結論是 updateDataSource 和 updateUI 函數耗盡了主線程。
func updateDataSource(model: [PairModel]) {
var snapshot = DiffableDataSourceSnapshot()
let diff = model.difference(from: snapshot.itemIdentifiers)
let currentIdentifiers = snapshot.itemIdentifiers
guard let newIdentifiers = currentIdentifiers.applying(diff) else {
return
}
snapshot.appendSections([.first])
snapshot.deleteItems(currentIdentifiers)
snapshot.appendItems(newIdentifiers)
dataSource?.apply(snapshot, animatingDifferences: false, completion: nil)
}
func updateUI(data: SocketData) {
guard let newData = data.data else { return }
guard let current = data.data?.price else { return }
guard let closed = data.data?.lastDayClosePrice else { return }
let dailyChange = ((current - closed)/closed)*100
DispatchQueue.main.async { [self] in
if model.filter({ $0.symbol == newData.pairSymbol }).first != nil {
let index = model.enumerated().first(where: { $0.element.symbol == newData.pairSymbol})
guard let location = index?.offset else { return }
model[location].price = current
model[location].dailyPercent = dailyChange
if calculateLastSignalTime(alertDate: model[location].alertDate) > 0 {
//Do Nothing
} else {
model[location].alertDate = ""
model[location].alertType = ""
}
if let text = allSymbolsView.searchTextField.text {
if text != "" {
filteredModel = model.filter({ $0.name.contains(text) || $0.symbol.contains(text) })
updateDataSource(model: filteredModel)
} else {
filteredModel = model
updateDataSource(model: filteredModel)
}
}
}
delegate?.pricesChange(data: self.model)
}
}
問候。
您的所有代碼都在主線程上運行。 您必須將整個updateUI
function 包裝在DispatchQueue.global(qos:)
中,然后將dataSource.apply(snapshot)
線包裝在DispatchQueue.main.async
中。 dataSource.apply(snapshot)
行是您在發布的所有代碼中所做的唯一 UI 工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.