Swift 删除Firebase数据时更新tableview行时遇到问题

Swift 删除Firebase数据时更新tableview行时遇到问题,swift,firebase,firebase-realtime-database,tableview,Swift,Firebase,Firebase Realtime Database,Tableview,在删除Firebase数据后尝试更新tableview的行时出错 下面是我使用的方法 func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, index

在删除Firebase数据后尝试更新tableview的行时出错

下面是我使用的方法

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in

        let cell = self.messages[indexPath.row]
        let b = cell.msgNo

        let action = MyGlobalVariables.refMessages.child(MyGlobalVariables.uidUser!)
        action.queryOrdered(byChild: "msgNo").queryEqual(toValue: b).observe(.childAdded, with: { snapshot in

            if snapshot.exists() { let a = snapshot.value as? [String: AnyObject]

                let autoId = a?["autoID"]

                action.child(autoId as! String).removeValue()

                self.messages.remove(at: indexPath.row)

                tableView.deleteRows(at: [indexPath], with: .automatic)
            } else {
                print("snapshot empty")
            }}) }
   ...
   return [delete, edit, preview]
}
最初,我检查了整个逻辑,但没有将line/*action.childautoId作为一个选项!String.removeValue*/然后它正常工作并按原样删除行。但一旦我添加这一行,它就会从Firebase中删除数据,但tableview会以一种奇怪的方式进行更新,即在现有行下方添加新行


我的猜测是,在应用程序的其他地方,您有类似action.observe.value的代码,它在表视图中显示数据。从数据库中删除节点时,将再次触发填充数据库的代码,并将删除节点后的相同数据再次添加到表视图中

使用Firebase时,最好遵循这一原则,这意味着您将修改数据的代码与显示数据的流完全分开。这意味着删除数据的代码不应尝试更新表视图。更像是:

let action = MyGlobalVariables.refMessages.child(MyGlobalVariables.uidUser!)
action.queryOrdered(byChild: "msgNo").queryEqual(toValue: b).observe(.childAdded, with: { snapshot in
    if snapshot.exists() { let a = snapshot.value as? [String: AnyObject]
        let autoId = a?["autoID"]
        action.child(autoId as! String).removeValue()
    } else {
        print("snapshot empty")
    }}) }
以上所做的只是从数据库中删除所选消息

现在,您可以专注于您的观察者,并确保它只显示一次消息。有两种选择:

在从数据库添加消息之前,当调用.value完成处理程序时,始终清除self.messages。这是目前为止最简单的方法,但如果显示大量数据,可能会导致一些闪烁。 收听更细粒度的消息,如.childAdded和.childRemoved,并根据这些消息更新self.messages。这在您的代码中需要做更多的工作,但当有许多消息时,将产生更平滑的UI。
我不明白什么地方出了问题,如果有任何建议或解决办法,我将不胜感激。谢谢你,弗兰克。刚刚在child.removeValue行之前添加了self.messages.removeAll,并在之后添加了self.tableView.reloadData和DispatchQueue.main.async,并且似乎开始正常工作