如何在swift 2.0中从sqlite数据库中滑动并删除选定的表视图行数据?

时间:2016-07-31 17:48:30

标签: ios swift sqlite

我使用了fmdb sqlite数据库包装器。我很困惑地获取选定的行标签文本。我的困惑是,当我滑动并删除tableView行时,整行也将从具有currentCell.userID.text的数据库中删除。那么,怎么做?提前致谢。 代码我试过,

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    let index = tableView.indexPathForSelectedRow
    let currentCell = tableView.cellForRowAtIndexPath(index!) as! DashBoardCell
    print(currentCell.userID.text)  //I am getting  NiL

    let deletedID = currentCell.userID.text

    if editingStyle == .Delete
    {

        let tableData = indexPath.row

        items.removeAtIndex(tableData)
        number.removeAtIndex(tableData)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

        let filemgr = NSFileManager.defaultManager()
        let dirPaths = filemgr.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)

        databasePath = dirPaths[0].URLByAppendingPathComponent("visitors.db").path!

        let contactDB = FMDatabase(path: self.databasePath as String)
        if contactDB.open()
        {
            let deleteSQL = "SELECT * FROM VISITORLIST WHERE userid = '\(deletedID)'"
            let result = contactDB.executeUpdate(deleteSQL, withArgumentsInArray: nil)
            if !result
            {
                print("Failed To Delete Visitor Lists")
                print("Error3: ",contactDB.lastErrorMessage())
            }
            else
            {
                print("Successfully Deleted")

            }

        }
        else
        {
            print("Error4: ",contactDB.lastErrorMessage())
        }

        tableView.reloadData()
    }
}

2 个答案:

答案 0 :(得分:1)

您不应该使用let index = tableView.indexPathForSelectedRow,您应该只使用indexPath。您当前的代码是从表数据中删除正确的对象,但是从SQLite存储中删除了错误的对象(如果没有选择任何行,则没有任何内容)。

答案 1 :(得分:1)

 let deleteSQL = "SELECT * FROM VISITORLIST WHERE userid = '\(deletedID)'"

应该是:

 let deleteSQL = "DELETE FROM VISITORLIST WHERE userid = '\(deletedID)'"

:)