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?