我有这段代码,每次单击按钮并调用另一个viewcontroller时都会调用它,在viewWillappear中调用fetchVinylData。问题是每次我单击一个按钮转到该VC时,即使我的数据库中只有一个条目,它也会向表视图中添加一个条目。我猜测是因为即使我的数据库中只有一条记录,我的数组也会不断被读取我如何从数组中删除,以使我的table中没有很多值,仅查看保存在Firebase数据库中的值?我尝试在将乙烯基加载到数组之前在fetchrequest中添加myArray.removeAll()。我的应用最终崩溃了
func fetchVinylData() {
SVProgressHUD.show()
guard let currentUID = Auth.auth().currentUser?.uid else { return }
dbRef.child("vinylsOUT").child(currentUID).observe(.childAdded) { (snapshot) in
guard let dictionary = snapshot.value as? Dictionary<String,AnyObject> else { return }
let vinyl = Vinyl(dictionary: dictionary)
self.vinyls.append(vinyl)
self.vinyls.sort(by: { (vinyl1, vinyl2) -> Bool in
return vinyl1.artist < vinyl2.artist
})
self.tableView.reloadData()
}
SVProgressHUD.dismiss()
}
非常感谢您
答案 0 :(得分:0)
每次从Firebase取回数据时,您都将追加到数组: -self.vinyls.append(乙烯基)
您可以通过执行以下操作来覆盖当前的乙烯基阵列:
self.vinyls = [Vinyl]()
从Firebase提取新数据之前。 看起来像这样:
func fetchVinylData() {
SVProgressHUD.show()
guard let currentUID = Auth.auth().currentUser?.uid else { return }
self.vinyls = [Vinyl]() // <- here you reset the array
dbRef.child("vinylsOUT").child(currentUID).observe(.childAdded) { (snapshot) in
guard let dictionary = snapshot.value as? Dictionary<String,AnyObject> else { return }
let vinyl = Vinyl(dictionary: dictionary)
self.vinyls.append(vinyl)
self.vinyls.sort(by: { (vinyl1, vinyl2) -> Bool in
return vinyl1.artist < vinyl2.artist
})
self.tableView.reloadData()
}
SVProgressHUD.dismiss()
}