Noah-1
Noah-1

Reputation: 396

Deleting wrong ID on Firebase

iIm trying to delete an item from Firebase and I am running into a strange problem. Here is the function:

     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)


    }

}

The problem is that every time I delete an item the next one is deleted in Firebase, not the one I selected. When I get to the end of the array I get the error "index out of range". Im guessing it has to do with the indexpath/array positions?

Thanks in advance!

Upvotes: 0

Views: 136

Answers (1)

faircloud
faircloud

Reputation: 727

It looks like you are removing the item from the array before you are getting the id that you are telling Firebase to delete. So for each item, you would actually be getting the id of the next item in the array when the array is reindexed following the deletion. If you tried this with the last item you would delete the last item, the array would change to size of n - 1 and then you would be trying to read location n, leading to an out of range error.

Try removing the item from the array after you retrieve the id for the Firebase deletion.

 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)


    }

}

Upvotes: 2

Related Questions