Duplicate Data from Firebase when I use .value

99封情书 提交于 2020-06-23 14:07:37

问题


I get duplicate data (old and updated data) in my UITableView whenever I update my data from firebase.

I am actually trying to create a realtime database for my UITableView.

var foodlist = [FoodModel]()

@objc func load_data() {
  Database.database().reference().child("Food").observe(.value) {
    (snapshot: DataSnapshot) in

    if let dict = snapshot.value as ? [String: AnyObject] {
      for child in dict.values {
        if let FoodimageText = child["image"] as ? String,
          let FoodnameText = child["name"] as ? String,
            let FoodpriceText = child["price"] as ? String {
              let post = FoodModel(FoodimageText: FoodimageText, FoodnameText: FoodnameText, FoodpriceText: FoodpriceText)
              self.foodlist.append(post)
            }
      }
      DispatchQueue.main.async {
        self.tableview_controller.reloadData()
      }
    }
  }
}

回答1:


var foodlist = [FoodModel]()

@objc func load_data() {
  Database.database().reference().child("Food").observe(.value) {
    (snapshot: DataSnapshot) in
    if let dict = snapshot.value as ? [String: AnyObject] {
      self.foodlist.removeAll() //add this
      for child in dict.values {
        if let FoodimageText = child["image"] as ? String,
          let FoodnameText = child["name"] as ? String,
            let FoodpriceText = child["price"] as ? String {
              let post = FoodModel(FoodimageText: FoodimageText, FoodnameText: FoodnameText, FoodpriceText: FoodpriceText)
              self.foodlist.append(post)
            }
      }
      DispatchQueue.main.async {
        self.tableview_controller.reloadData()
      }
    }
  }
}



回答2:


first check you only received one row of the data or complete nodes, sometimes you received complete data from firebase when adding a new row, if you received complete data from the firebase so, remove all items from the array after that append data in the array.

try this before calling the listener, foodlist.removeAll()



来源:https://stackoverflow.com/questions/62512632/duplicate-data-from-firebase-when-i-use-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!