Created
February 19, 2023 23:03
-
-
Save andresr-dev/47e6e23920358b0127291313b18a1382 to your computer and use it in GitHub Desktop.
This is how to perform a batch delete in CoreData
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private func delete(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) { | |
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) | |
// Tell me the ids of the objects that you are going to delete | |
batchDeleteRequest.resultType = .resultTypeObjectIDs | |
// execute the deletion at the SQL level | |
if let deleteResult = try? container.viewContext.execute(batchDeleteRequest) as? NSBatchDeleteResult { | |
// get the IDs of the objects deleted | |
if let objectIDs = deleteResult.result as? [NSManagedObjectID] { | |
// Merge the deletions into the app's managed object context. | |
// We must always do this after performing a batch delete, because a batch delete | |
// just remove objects from disk (at SQL level) but not from memory (viewContext). | |
NSManagedObjectContext.mergeChanges( | |
fromRemoteContextSave: [NSDeletedObjectsKey: objectIDs], | |
into: [container.viewContext] | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment