如何使用Swift从tableview和sqlite3中删除

问题描述 投票:1回答:1

我是swift和sqlite3的新手,我需要有关如何从tableview和sql db中删除的帮助。

我试图使用reloadData()但它不起作用。我试图删除使用tableView.deleteRows(at: [indexPath], with: .fade)但我得到一个错误,因为我有一个sql删除语句运行之前。使用下面提供的代码,我成功地从数据库中删除了该项,但它没有刷新tableview。我暂时修复它的方法是在成功删除项目后执行上一屏幕的segue,当返回到tableviewcontroller时,它将被删除。

import UIKit

class TableViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    let mainDelegate = UIApplication.shared.delegate as! AppDelegate
    @IBOutlet var tableView: UITableView!
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let tableCell = tableView.dequeueReusableCell(withIdentifier: "cell") as? SiteCell ?? SiteCell(style: .default, reuseIdentifier: "cell")
        let rowNum = indexPath.row
        tableCell.primaryLabel.text = mainDelegate.people[rowNum].name
        tableCell.secondaryLabel.text = mainDelegate.people[rowNum].email
        tableCell.myImageView.image = UIImage(named: mainDelegate.people[rowNum].avatar!)
        tableCell.accessoryType = .disclosureIndicator
        return tableCell
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return mainDelegate.people.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let rowNum = indexPath.row
        let details : String! =  "Address: \(mainDelegate.people[rowNum].address!) \nPhone Num: \(mainDelegate.people[rowNum].phonenum!) \nEmail: \(mainDelegate.people[rowNum].email!) \nAge: \(mainDelegate.people[rowNum].age!) \nGender: \(mainDelegate.people[rowNum].gender!) \nDate of birth: \(mainDelegate.people[rowNum].dob!)"
        let alertController = UIAlertController(title: mainDelegate.people[rowNum].name, message: details, preferredStyle: .alert
        )
        let cancelAction = UIAlertAction(title: "ok", style: .cancel, handler: nil)
        print("TESTING ROW: \(mainDelegate.people[rowNum].id!)")
        alertController.addAction(cancelAction)
        present(alertController, animated: true)
    }

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    var rowNum: Int = indexPath.row
        if editingStyle == .delete {
            print("Testing delete \(mainDelegate.people[rowNum].id!)")
            print("\(indexPath.row)")

            mainDelegate.removeFromDatabase(id: mainDelegate.people[rowNum].id!)
            print("\(indexPath)")
//            tableView.deleteRows(at: [indexPath], with: .fade)

            DispatchQueue.main.async{
                self.tableView.reloadData()
            }
//            self.performSegue(withIdentifier: "DataToInfo", sender: self)

//          let mainDelegate = UIApplication.shared.delegate as! AppDelegate
//          mainDelegate.removeFromDatabase(person: mainDelegate.people[indexPath.row])
            }
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        mainDelegate.readDataFromDatabase()
    }

removeFromDatabase方法

func removeFromDatabase(id : Int){

        var db : OpaquePointer? = nil

        if sqlite3_open(self.databasePath, &db) == SQLITE_OK{

            print("Successfully opened connection to database at \(self.databasePath)")
            var deleteStatement : OpaquePointer? = nil
            let deleteStatementString : String = "delete from entries where id=\(id)"
            if sqlite3_prepare_v2(db, deleteStatementString, -1, &deleteStatement, nil) == SQLITE_OK{
                if sqlite3_step(deleteStatement) == SQLITE_DONE{
                    print("Deleted")
                }
                else{
                    print("Failed")
                }
            }else{
                print("Couldn't prepare")
            }
            sqlite3_finalize(deleteStatement)

            sqlite3_close(db)
        }
    }

我试图从tableview和数据库中删除它。有一次我试图mainDelegate.people.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade)然后运行removeFromDatabase,但它给了我一个错误。

ios swift tableview reloaddata swift4.2
1个回答
0
投票

您应该更新数据源。尝试像这样重构你的commitEditing:

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
var rowNum: Int = indexPath.row
    if editingStyle == .delete {
        print("Testing delete \(mainDelegate.people[rowNum].id!)")
        print("\(indexPath.row)")

        mainDelegate.removeFromDatabase(id: mainDelegate.people[rowNum].id!)
        print("\(indexPath)")


        mainDelegate.readDataFromDatabase()


        tableView.deleteRows(at: [indexPath], with: .fade)


        }
}
© www.soinside.com 2019 - 2024. All rights reserved.