Using NSFetchedResultsController w/NSBatchDeleteRequest

From Apple's documentation:

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 the Updating Your Application After Execution section for handling the objects deleted by NSBatchDeleteRequest.


Here is the sample, works for me. But i didn't find how to update deletion with animation, cause NSFetchedResultsControllerDelegate didn't fire.

@IBAction func didPressDelete(_ sender: UIBarButtonItem) {
        let managedObjectContext = persistentContainer.viewContext
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: Record.self))
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: request)

        do {
            // delete on persistance store level
            try managedObjectContext.execute(deleteRequest)

            // reload the whole context
            managedObjectContext.reset()
            try self.fetchedResultsController.performFetch()
            tableV.reloadData()
        } catch {
            print("")
        }
    }

Thanks.