2017-01-24 7 views
0

Firebaseからアイテムを削除しようとしていて、私は奇妙な問題に遭遇しています。ここ 機能です:Firebaseで間違ったIDを削除する

 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 /配列の位置と関係していると思いますか?

ありがとうございます!

+0

あなたはそれが間違って起こっている場所を確認するために、各段階でindexPathをログアウトすることはできますか? – brandonscript

答えて

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) 


    } 

} 
関連する問題