Search code examples
ioscore-datansmanagedobjectcontext

Delete all core data records does not set hasChanges in managedContext


I am new to coreData, and I have a problem:

My app executes the following 3 successive core data functions:

    let managedContext = persistentContainer.viewContext
    deleteAllCDRecords(managedContext: managedContext, in: "CDShoppingItem")
    saveManagedContext(managedContext: managedContext)  

They are defined (shortened) as:

private func deleteAllCDRecords(managedContext: NSManagedObjectContext, in entity: String) {
    let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
    do {
        try managedContext.execute(deleteRequest)
    } catch let error as NSError {
        // error handling
    }
} // deleteAllCDRecords  

and

private func saveManagedContext(managedContext: NSManagedObjectContext) {
    if !managedContext.hasChanges { return }
    do {
        try managedContext.save()
    } catch let error as NSError {
        // error handling
    }
} // saveManagedContext  

The problem:

After deleteAllCDRecords is executed, managedContext.hasChanges in function saveManagedContext is not true, thus the deletion is not saved to the persistent store.

My question:
What is wrong with my code?


Solution

  • Batch deletes operate in the persistent store itself. So in this special case you delete the entities from the persistent store and have to remove the objects in memory afterwards.

    Batch deletes run faster than deleting the Core Data entities yourself in code because they operate in the persistent store itself, at the SQL level. As part of this difference, the changes enacted on the persistent store are not reflected in the objects that are currently in memory.

    After a batch delete has been executed, remove any objects in memory that have been deleted from the persistent store.

    See https://developer.apple.com/library/archive/featuredarticles/CoreData_Batch_Guide/BatchDeletes/BatchDeletes.html.