快速致命错误索引超出表视图上的范围问题.重新加载数据



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

提前感谢您的帮助

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

return self.data.count

第二(result(

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

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

最新更新