Skip to content

Instantly share code, notes, and snippets.

@andresr-dev
Created February 19, 2023 23:03
Show Gist options
  • Save andresr-dev/47e6e23920358b0127291313b18a1382 to your computer and use it in GitHub Desktop.
Save andresr-dev/47e6e23920358b0127291313b18a1382 to your computer and use it in GitHub Desktop.
This is how to perform a batch delete in CoreData
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