Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to batch delete in Core Data #622

Open
onmyway133 opened this issue Mar 15, 2020 · 0 comments
Open

How to batch delete in Core Data #622

onmyway133 opened this issue Mar 15, 2020 · 0 comments

Comments

@onmyway133
Copy link
Owner

Read Implementing Batch Deletes

If the entities that are being deleted are not loaded into memory, there is no need to update your application after the NSBatchDeleteRequest has been executed. However, if you are deleting objects in the persistence layer and those entities are also in memory, it is important that you notify the application that the objects in memory are stale and need to be refreshed.

To do this, first make sure the resultType of the NSBatchDeleteRequest is set to NSBatchDeleteRequestResultType.resultTypeObjectIDs before the request is executed. When the request has completed successfully, the resulting NSPersistentStoreResult instance that is returned will have an array of NSManagedObjectID instances referenced in the result property. That array of NSManagedObjectID instances can then be used to update one or more NSManagedObjectContext instances.

let fetchRequest: NSFetchRequest<NSFetchRequestResult> = Book.fetchRequest()
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
deleteRequest.resultType = .resultTypeObjectIDs

do {
    let context = CoreDataManager.shared.container.viewContext
    let result = try context.execute(
        deleteRequest
    )

    guard
        let deleteResult = result as? NSBatchDeleteResult,
        let ids = deleteResult.result as? [NSManagedObjectID]
    else { return }

    let changes = [NSDeletedObjectsKey: ids]
    NSManagedObjectContext.mergeChanges(
        fromRemoteContextSave: changes,
        into: [context]
    )
} catch {
    print(error as Any)
}
@onmyway133 onmyway133 changed the title How to batch request in Core Data How to batch delete in Core Data Mar 15, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant