Reputation: 7
I'm having an error when trying to delete from UITableView. My TableView is from CoreData. Here is my code.
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == UITableViewCellEditingStyle.delete) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
context.delete(mealCore[indexPath.row])
appDelegate.saveContext()
print("context saved")
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
my context is getting saved. But when it tries to delete it from the tableview, it crashes with the following errror:
Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (5) must be equal to the number of rows contained in that section before the update (5), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).
Would really appreciate any advice. Thanks!!!
Just adding the some codes that might help? I might be doing something wrong: var mealCore = NSManagedObject public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CustomTableViewCell
let dateFormatter = DateFormatter()
dateFormatter.dateFormat="dd/mm/yyyy"
let mealRec = mealCore[indexPath.row]
cell.mealName!.text = mealRec.value(forKey: "meal") as? String
if let dateHolder = mealRec.value(forKey: "mealdate"){
cell.mealDate.text = dateFormatter.string(from: dateHolder as! Date)
}
if let data = mealRec.value(forKey: "mealimage")as? NSData {
cell.mealImage?.image = UIImage(data: data as Data)
}
return cell
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"FoodLog")
do {
let results = try managedContext.fetch(fetchRequest)
mealCore = results as! [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mealCore.count
}
Upvotes: 0
Views: 2814
Reputation: 4884
You need to delete object from mealCore
array.
Swift 3
mealCore.remove(atIndex: indexPath.row)
Swift 4
mealCore.remove(at: indexPath.row)
Upvotes: 5
Reputation: 6159
Try making a call to beginUpdates
and endUpdates
like so:
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.endUpdates()
Upvotes: -1