tableView.reloadData上的Swift致命错误索引超出范围问题

tableView.reloadData上的Swift致命错误索引超出范围问题,swift,reloaddata,Swift,Reloaddata,我正在为iOS手机开发Swift应用程序,我是android开发者,从iOS开始 我在从RealmSwift数据库添加数据后重新加载数据时遇到问题 我使用了tableView.reloadData,但有一个致命错误导致索引超出范围 这是我的密码: class CarsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { let realm = try! Realm() @IBOutle

我正在为iOS手机开发Swift应用程序,我是android开发者,从iOS开始

我在从RealmSwift数据库添加数据后重新加载数据时遇到问题

我使用了tableView.reloadData,但有一个致命错误导致索引超出范围

这是我的密码:

class CarsViewController: UIViewController,   UITableViewDelegate, UITableViewDataSource {


let realm = try! Realm()
@IBOutlet weak var tableViewCar: UITableView!

var data:Results<Car>!
var result:[Car] = []
var isEditingMode = false

func listCars(){
    self.data = realm.objects(Car.self)
    self.result = Array(self.data)
    self.tableViewCar.setEditing(false, animated: true)
    self.tableViewCar.reloadData()
    print("listCars")
}

var db: OpaquePointer? // Définition de la base de données
var cars = [Car]()

override func viewDidLoad() {
    super.viewDidLoad()
    print("Realm DB : \(Realm.Configuration.defaultConfiguration.fileURL!)")
    listCars()
    self.navigationItem.leftBarButtonItem = self.editButtonItem
    NotificationCenter.default.addObserver(self, selector: #selector(loadView), name: NSNotification.Name(rawValue: "load"), object: nil)
}

func loadList(notification: NSNotification){
    //load data here
    if(self.data.count > 0){
        self.tableViewCar.reloadData()
    }
}

@IBAction func didClickEditCar(_ sender: UIBarButtonItem) {
    isEditingMode = !isEditingMode
    self.tableViewCar.setEditing(isEditingMode, animated: true)
}

func displayCars() {

}

/* Suppression d'un élément par son id */
func delete(id: Int) -> Void {

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}   


func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let deleteAction = UITableViewRowAction(style: .default, title: "Supprimer") { (deleteAction, indexPath) -> Void in

        //Deletion will go here

        let listToBeDeleted = self.result[indexPath.row]

        let deleteCarAlert = UIAlertController(title: "Suppression voiture", message: "Etes-vous sûr de vouloir supprimer la voiture sélectionnée ?", preferredStyle: UIAlertControllerStyle.alert)

        deleteCarAlert.addAction(UIAlertAction(title: "Oui", style: .default, handler: { (action: UIAlertAction!) in
            print("L'utilisateur a décidé de supprimer un véhicule")
            try! self.realm.write{
                self.realm.delete(listToBeDeleted)
                self.toastMessage("La voiture a bien été supprimée de la base")
                self.listCars()
            }
        }))

        deleteCarAlert.addAction(UIAlertAction(title: "Non", style: .cancel, handler: { (action: UIAlertAction!) in
            print("Handle Cancel Logic here")
        }))

        self.present(deleteCarAlert, animated: true, completion: nil)
    }
    /*let editAction = UITableViewRowAction(style: UITableViewRowActionStyle.normal, title: "Edit") { (editAction, indexPath) -> Void in

     // Editing will go here
     let listToBeUpdated = self.lists[indexPath.row]
     self.displayAlertToAddTaskList(listToBeUpdated)

     }*/

    return [deleteAction]
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.data.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    //tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CarTableViewCell")
    let cell = tableView.dequeueReusableCell(withIdentifier: "CarCell", for: indexPath) as! CarTableViewCell

    // Configure the cell...
    cell.CarMarque?.text = self.result[indexPath.row].modele
    cell.CarPseudo?.text = self.result[indexPath.row].pseudo
    cell.CarImmatriculation?.text = self.result[indexPath.row].immatriculation
    let carImage = UIImage(data: self.result[indexPath.row].data! as Data)
    cell.CarImage?.image = carImage
    //cell.CarImage?.image = self.result[indexPath.row].image

    return cell
}


// Override to support editing the table view.
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        // Delete the row from the data
        let id = indexPath.row
        delete(id: id)
        tableView.deleteRows(at: [indexPath], with: .fade)

    } else if editingStyle == .insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }    
}

override func viewWillAppear(_ animated: Bool){
    super.viewWillAppear(true)
    //tableViewCar.reloadData()

}

提前感谢您的帮助

这是因为您首先在此处使用了两个数组数据

第二个结果

最初两者的计数相同,然后在删除时从结果中删除项,然后重新加载,这会导致它们的计数不匹配,从而导致崩溃,所以最好使用1个数组

// Configure the cell...
cell.CarMarque?.text = self.result[indexPath.row].modele
return self.data.count
cell.CarMarque?.text = self.result[indexPath.row].modele