Tung Fam Tung Fam - 2 months ago 8
Swift Question

Deletion in CoreData doesn't delete; deleted object appears after relaunching

My code of deletion of object from core data:

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// removing from core data
let managedContext = DataController().managedObjectContext
managedContext.delete(books[indexPath.row] as NSManagedObject)
books.remove(at: indexPath.row)
do {
try managedContext.save()
// I debug on this step : "po books" and I do see that the book was deleted from the books. even more there is no errors.
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
// Delete the row from the data source (from table view)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}


So after deleting the book. It disappears from the table view and also it is removed from the books (core data entity).

But then I relaunch the app and the deleted book will appear again (as it was never deleted before).

I found this: link

But unfortunately it doesn't make much sense because of some commits etc. I'm storing on core data which is locally on device.

May be these codes may help:

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

let managedContext = DataController().managedObjectContext
let fetchRequest: NSFetchRequest<Book> = Book.fetchRequest()
do {
let results =
try managedContext.fetch(fetchRequest)
books = results
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
booksListTableView.reloadData()
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: bookCellIdentifier, for: indexPath) as! ShowDataTableViewCell
let index = (indexPath as NSIndexPath).row
let book = books[indexPath.row]
cell.valueLabel.text = book.value(forKey: "bookName") as! String?
return cell
}


Thanks in advance!

Answer

When you save a managed object context it saves it to its parent context. That doesn't necessarily mean it is saved to disk.

To save to disk you need to save the persistent store. If you create a new application in Xcode and choose "Use Core Data" you will see code in the app delegate that does this in applicationWillTerminate.