我有一個顯示所有新聞的 tableView,然后如果有任何新聞更新或添加了新新聞,我將按如下方式檢查和更新。我想知道我的方法是否正確并且還在尋找更好的選擇(tableviewdiffsource?)
當前用戶按順序看到以下 4 條新聞
[n1, n2, n3, n4]
當用戶拉動重繪 時,他從服務器獲得 3 個訊息:[n4, n5, n6]
現在我應該按這個順序顯示新聞 [n4, n5, n6, n1, n2, n3]
var allNews = [News]()
func didFetchNews(newNews:[News]) {
var news:[News] = newNews
var newsSet = Set(newNews)
var deletedPaths = [IndexPath]()
for i in 0..<allNews.count {
let news = allNews[i];
if !newsSet.contains(news) {
news.append(news)
} else {
deletedPaths.append(IndexPath(row: i, section: 0))
}
}
var insertedPath = [IndexPath]()
for i in 0..<newNews.count {
insertedPath.append(IndexPath(row: i, section: 0))
}
self.tableView.beginUpdates()
self.tableView.insertRows(at: insertedPath, with: .automatic)
self.tableView.deleteRows(at: deletedPaths, with: .automatic)
self.tableView.endUpdates()
}
uj5u.com熱心網友回復:
DiffableDataSource 可能是最有效的解決方案。
但是,您的代碼也可以通過使用更高級別的函式(如filter和 )來優化map。
首先計算更新新聞的索引。當新專案插入頂部時,插入索引路徑等于新專案的索引。
然后在過濾后的索引處洗掉專案,并在索引 0 處插入新專案。reversed()避免超出范圍的崩潰。
func didFetchNews(newNews: [News]) {
let deletionIndices = allNews.indices.filter{newNews.contains(allNews[$0])}
let deletionIndexPaths = deletionIndices.map{IndexPath(row: $0, section: 0)}
let insertionIndexPaths = newNews.indices.map{IndexPath(row: $0, section: 0)}
for index in deletionIndices.reversed() { allNews.remove(at: index) }
allNews.insert(contentsOf: newNews, at: 0)
self.tableView.beginUpdates()
self.tableView.insertRows(at: insertionIndexPaths, with: .automatic)
self.tableView.deleteRows(at: deletionIndexPaths, with: .automatic)
self.tableView.endUpdates()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/326564.html
