【问题标题】:update changes in array from server swift从服务器 swift 更新数组中的更改
【发布时间】:2018-03-26 13:10:39
【问题描述】:

我有一个从 FireBase 获取数据,将其保存在本地并将其加载到 UITableView 中的方法。效果很好。

现在,这个观察者 (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()
            }
        }
    })

【问题讨论】:

  • 我认为您可以使用.childChanged 事件类型来检测指定引用的孩子何时更新或更改

标签: ios swift uitableview firebase


【解决方案1】:

如果你想更新特定的索引路径使用

tableView.reloadRows(at: your_indexpath_array, with: your_Animation)

在表中插入新行使用

 tableView.beginUpdates()
 tableView.insertRows(at: your_indexpath_array, with: your_Animation)
 tableView.endUpdates()

【讨论】:

  • 谢谢,但这不是我问的。请阅读问题,我知道如何更新 UITableView 单元格
【解决方案2】:

试试这个:

rootGenerals.observe(.childAdded, with: { snapshot in
    //your code
})

所以每次添加新的子用户时,它只会读取新数据

【讨论】:

  • 但是如果孩子更新了没有添加呢?在服务器中更新的数据与 tableview 中属于它的同一行之间进行同步的最佳方式是什么?
  • 当您刚刚运行您的应用程序时,首先它会读取您 Firebase 中的每个子项。如果在代码已经运行时添加了新的孩子,它将只读新的孩子。然后您可以重新加载整个表格或仅将新行插入您的表格中。对于孩子的更新,对于改变的孩子有类似的方法。希望我回答了所有问题,您可以在此处找到官方文档中的所有方法firebase.google.com/docs/database/ios/lists-of-data
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-17
相关资源
最近更新 更多