Search code examples
xcodeswift3sqlite

Delete on swipe, removes first item in the list when you swipe any one


Every time I swipe item in table view and delete it, it deletes the first item in the list, not the one I swipe. I tried different approaches but still doing the same

Here is my view controller function, where I swipe and call delete method.

func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? 
{

let modifyAction = UIContextualAction(style: .normal, title: "Modify", handler:
        { ac, view, success in
            var stmt: OpaquePointer?

            let deleteStatementStirng = "SELECT * FROM ShoppingList"
            if sqlite3_prepare(self.db, deleteStatementStirng, -1, &stmt, nil) != SQLITE_OK
            {
                print("error preparing delete")
            }

            if sqlite3_step(stmt) == SQLITE_ROW {
                let id = sqlite3_column_int(stmt, 0)
                self.deleteRow(itemId: Int32(id))
            }
            success(true)
        }
    )

    modifyAction.backgroundColor = .red
    return UISwipeActionsConfiguration(actions: [modifyAction])
}

And also my delete function:

func deleteRow(itemId: Int32){
        let deleteStatementStirng = "DELETE FROM ShoppingList WHERE id = \(itemId)"

        var deleteStatement: OpaquePointer?

        if sqlite3_prepare(db, deleteStatementStirng, -1, &deleteStatement, nil) == SQLITE_OK{

            if sqlite3_step(deleteStatement) == SQLITE_DONE {
                print("Successfully deleted row.")
            } else {
                print("Could not delete row.")
            }
        } else {
            print("DELETE statement could not be prepared")
        }

        sqlite3_finalize(deleteStatement)
        readValues()

    }

Expected result is to delete item from the list


Solution

  • Just update your modifyAction code with: (Added indexPath.row instead 0 while getting id)

    let modifyAction = UIContextualAction(style: .normal, title: "Modify", handler:
        { ac, view, success in
            var stmt: OpaquePointer?
    
            let deleteStatementStirng = "SELECT * FROM ShoppingList"
            if sqlite3_prepare(self.db, deleteStatementStirng, -1, &stmt, nil) != SQLITE_OK
            {
                print("error preparing delete")
            }
    
            if sqlite3_step(stmt) == SQLITE_ROW {
                let id = sqlite3_column_int(stmt, indexPath.row)
                self.deleteRow(itemId: Int32(id))
            }
            success(true)
        }
    )