【问题标题】:Deleting wrong ID on Firebase在 Firebase 上删除错误的 ID
【发布时间】:2017-01-24 20:57:00
【问题描述】:

我正在尝试从 Firebase 中删除一个项目,但我遇到了一个奇怪的问题。 这是函数:

     func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {

        //delete item from array
        itemArray.remove(at: indexPath.row)

        // delete from database
        var itemRef = FIRDatabaseReference()
        ref = FIRDatabase.database().reference()
        let userID = FIRAuth.auth()?.currentUser?.uid

        let idDel =  itemArray[indexPath.row].itemID
        itemRef = self.ref.child(userID!).child("ShoppingCart").child(idDel!)
        itemRef.removeValue()

        //delete row
        cartTable.deleteRows(at:[indexPath], with: .fade)


    }

}

问题是每次我删除一个项目时,Firebase 中都会删除下一个项目,而不是我选择的项目。当我到达数组的末尾时,我收到错误“索引超出范围”。我猜它与索引路径/数组位置有关?

提前致谢!

【问题讨论】:

  • 能否在每个阶段注销 indexPath 看看哪里出错了?

标签: swift firebase tableview


【解决方案1】:

看起来您是在获取要告诉 Firebase 删除的 id 之前从数组中删除该项目。因此,对于每个项目,当数组在删除后重新索引时,您实际上将获得数组中下一个项目的 id。如果您对最后一项尝试此操作,您将删除最后一项,数组将更改为 n - 1 的大小,然后您将尝试读取位置 n,从而导致超出范围错误。

在检索到 Firebase 删除的 id 后,尝试从数组中删除该项目。

 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {

    // delete from database
    var itemRef = FIRDatabaseReference()
    ref = FIRDatabase.database().reference()
    let userID = FIRAuth.auth()?.currentUser?.uid

    let idDel =  itemArray[indexPath.row].itemID
    itemRef = self.ref.child(userID!).child("ShoppingCart").child(idDel!)
    itemRef.removeValue()

    //delete item from array
    itemArray.remove(at: indexPath.row)

    //delete row
    cartTable.deleteRows(at:[indexPath], with: .fade)


    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 2023-01-01
    • 2018-04-14
    • 1970-01-01
    • 2022-01-19
    • 2020-08-19
    相关资源
    最近更新 更多