我正在尝试从我的 firebase 数据库更新我的子值,但问题是每当我的子值增加 1 时,我的 tableview 就会自动创建一个新的子值。我怎样才能使它只更新子值?感谢您提前提供的帮助。
注意:请查看图片以更清楚地了解
var ref: DatabaseReference?
var databaseHandle: DatabaseHandle?
var postData = [String]()
var postData2 = [String]()
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference() //set the firebase reference
// Retrieve the post and listen for changes
databaseHandle = ref?.child("Posts").observe(.childChanged, with: { (snapshot) in
// Code to execute when a child is added under "Posts"
let post1 = snapshot.key
let post2 = (snapshot.value as AnyObject).description
postData.append(post1)
if let actualPost = post2 {
postData2.append(actualPost)
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return postData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = postData[indexPath.row]
cell.detailTextLabel?.text = postData2[indexPath.row] + " ★"
cell.detailTextLabel?.textColor = UIColor.yellow;
return cell
}
}
最佳答案
当您从列表中添加元素时,数据源计数会增加 1,但随后将调用 childAdded 的 Firebase 回调,现在您检索从数据库添加的相同元素,从而导致重复行。
您的示例中不存在按下红色按钮时运行的调用,但我假设您按照这些方式做了一些事情。希望对您有所帮助。
关于ios - 更改/更新子值而不添加新子项(Firebase-swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47503206/