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

时间:2018-10-16 21:44:59

标签: swift reloaddata

我正在为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()

}

我的问题在线了:

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

预先感谢您的帮助

1 个答案:

答案 0 :(得分:0)

这是因为您首先在这里使用2个数组(data

return self.data.count

和第二个(result

cell.CarMarque?.text = self.result[indexPath.row].modele

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