gpt4 book ai didi

tableView.reloadData 上的 Swift fatal error 索引超出范围问题

转载 作者:行者123 更新时间:2023-11-30 11:04:48 27 4
gpt4 key购买 nike

我正在为 iOS 手机开发 Swift 应用程序,我是 Android 开发人员,从 iOS 开始......

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

我使用了tableView.reloadData,但出现 fatal error ,导致索引超出范围。

这是我的代码:

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

第二个(结果)

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

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

关于tableView.reloadData 上的 Swift fatal error 索引超出范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52844447/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com