从服务器swift更新数组中的更改
我有一个方法从FireBase获取数据,将其保存在本地并将其加载到UITableView中。它运作良好。从服务器swift更新数组中的更改
现在,这个观察者(rootGenerals.observe())正在运行,并且每次在服务器上更改数据时都会进行更新。
我的问题是,我不想重新加载整个表,一旦我得到一个新的数据(就像我现在所做的那样),我只想更新表中具体更改的行或替换行的位置( IndexPath)如果分数已经改变。
任何想法如何做到这一点?只需要一些指导,了解在这种情况下处理的最佳方式。
rootGenerals.observe(.value, with: { snapshot in
if !snapshot.exists() { return }
let general = snapshot.value as! NSDictionary
if let users : NSDictionary = general.object(forKey: "users") as? NSDictionary
{
if (self.usersFromDB?.count != 0) {
// Update table rows
self.arrRecords = []
}
else {
// Create table from scratch
self.usersFromDB = users
for user : Any in users.allKeys {
let userDict : NSDictionary = users.object(forKey: user as! String) as! NSDictionary
let record : Record = Record()
record.displayName = userDict.object(forKey: "name") as! String
record.time = userDict.object(forKey: "time") as! Int
record.solvedLogos = userDict.object(forKey: "logos_solved") as! Int
record.deviceId = userDict.object(forKey: "device_id") as! String
record.raw = userDict
self.arrRecords.append(record)
}
self.sortRecords()
}
}
})
,如果你想要更新的特定索引路径使用
tableView.reloadRows(at: your_indexpath_array, with: your_Animation)
为表中的使用插入新行
tableView.beginUpdates()
tableView.insertRows(at: your_indexpath_array, with: your_Animation)
tableView.endUpdates()
谢谢,但这不是我问的问题。请阅读问题,我知道如何更新一个UITableView单元格 –
尝试使用这样的:
rootGenerals.observe(.childAdded, with: { snapshot in
//your code
})
所以每次添加新的儿童用户时,它只会读取n新数据
但是,如果孩子更新并未添加?什么是最好的方式来同步服务器中更新的和在tableview中属于它的同一行? –
当您刚刚运行您的应用程序时,它首先读取您的Firebase中的每个孩子。如果在代码已经运行时添加新的子代,它将只读取新的子代。然后,您可以重新加载整个表格或只在表格中插入新行。对于孩子的更新,对于更换的孩子也有类似的方法。希望我回答了所有问题,在这里您可以找到官方文档中的所有方法https://firebase.google.com/docs/database/ios/lists-of-data –
我想你可以使用'.childChanged'事件类型来检测指定引用的孩子何时更新或更改 – 3stud1ant3