NSBatchDeleteRequest with an NSFetchRequest<NSFetchRequestResult> for the target entity to delete all records directly in the SQLite store without loading them into memory. Set resultType = .resultTypeObjectIDs and pass the deleted object IDs to NSManagedObjectContext.mergeChanges(fromRemoteContextSave:into:) so your UI and active contexts stay in sync.Why this happens
When you refresh a local Core Data cache from a web service that returns a full dataset, you often need to clear the existing records first to avoid duplicates. Fetching every object in an entity, looping over the array, calling context.delete(_:), and saving works for small datasets, but it becomes slow and memory-intensive once you have thousands of records.
Each fetched NSManagedObject is loaded into the NSManagedObjectContext row cache, tracked for change notifications and undo management, and deleted with individual operations. If you only want to wipe a table clean, loading thousands of objects into memory just to remove them is unnecessary overhead.
How to fix it
1. Use NSBatchDeleteRequest and merge changes into your context
NSBatchDeleteRequest executes a single delete operation directly against the underlying SQLite persistent store, bypassing the managed object context in memory. Because it bypasses the context, any views or controllers holding fetched objects (such as SwiftUI @FetchRequest or NSFetchedResultsController) will not know the rows were deleted unless you merge the deleted object IDs back in.
import CoreData
func deleteAllRecords(of entityName: String, in context: NSManagedObjectContext) throws {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
deleteRequest.resultType = .resultTypeObjectIDs
let result = try context.execute(deleteRequest) as? NSBatchDeleteResult
if let objectIDs = result?.result as? [NSManagedObjectID], !objectIDs.isEmpty {
let changes: [AnyHashable: Any] = [NSDeletedObjectsKey: objectIDs]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [context])
}
}
If you run the batch delete on a background context created with persistentContainer.performBackgroundTask, pass both the background context and persistentContainer.viewContext in the into: array so your UI updates immediately on the main queue.
If you are maintaining an Objective-C codebase, the same batch delete pattern applies using NSPersistentStoreCoordinator or NSManagedObjectContext:
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Car"];
NSBatchDeleteRequest *deleteRequest = [[NSBatchDeleteRequest alloc] initWithFetchRequest:request];
deleteRequest.resultType = NSBatchDeleteRequestResultTypeObjectIDs;
NSError *error = nil;
NSBatchDeleteResult *result = (NSBatchDeleteResult *)[context executeRequest:deleteRequest error:&error];
if (result.result) {
NSDictionary *changes = @{ NSDeletedObjectsKey: result.result };
[NSManagedObjectContext mergeChangesFromRemoteContextSave:changes
intoContexts:@[context]];
}
2. Use NSBatchDeleteRequest with context.reset() for background imports
If you are wiping an entity inside a dedicated background import context that has no UI bound to it—and you are about to insert fresh objects from a network response—you do not always need to collect object IDs. You can execute the batch delete and call context.reset() to clear any stale in-memory state in that context.
import CoreData
func resetEntity(_ entityName: String, in container: NSPersistentContainer) throws {
let backgroundContext = container.newBackgroundContext()
try backgroundContext.performAndWait {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
try backgroundContext.execute(deleteRequest)
backgroundContext.reset()
}
}
Note that reset() only clears backgroundContext. If viewContext is observing the store at the same time, stick with Approach 1 so viewContext receives the deletion notifications.
3. Fall back to fetching object IDs for in-memory stores
NSBatchDeleteRequest only works with SQLite-backed persistent stores (NSSQLiteStoreType). If your app or unit test suite uses an in-memory store (NSInMemoryStoreType), executing NSBatchDeleteRequest throws an error because there is no SQLite store to execute the batch operation against.
In that case, fetch the objects with includesPropertyValues = false so Core Data only loads lightweight faults rather than full property data, then delete them in a loop and save:
import CoreData
func deleteAllInMemory(entityName: String, in context: NSManagedObjectContext) throws {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)
fetchRequest.includesPropertyValues = false
let objects = try context.fetch(fetchRequest)
for object in objects {
context.delete(object)
}
if context.hasChanges {
try context.save()
}
}
This approach is also useful when you rely on custom prepareForDeletion() overrides on your NSManagedObject subclasses, since NSBatchDeleteRequest does not instantiate managed objects or call lifecycle methods.
How to prevent it
- Consider unique constraints instead of full wipes: If your entities have a stable server identifier, configure a uniqueness constraint on the attribute in the Core Data model editor and set
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy. That lets you upsert records without purging the table first. - Run batch operations off the main thread: Always execute
NSBatchDeleteRequestand subsequent JSON parsing insideperformBackgroundTaskor a private queue context so the UI stays responsive. - Use
/dev/nullSQLite stores in unit tests: Instead ofNSInMemoryStoreType, pointNSPersistentStoreDescription.urltoURL(fileURLWithPath: "/dev/null")in tests. You get fast, non-persistent storage that still supportsNSBatchDeleteRequest. - Always merge or reset after a batch delete: Never assume
NSManagedObjectContextautomatically reflects batch changes made directly in SQLite.
FAQ
Does NSBatchDeleteRequest work with SwiftUI @FetchRequest?
Yes, provided you merge the deleted object IDs into viewContext using NSManagedObjectContext.mergeChanges(fromRemoteContextSave:into:). Without merging, @FetchRequest will continue displaying stale objects until the context is refreshed or the app restarts.
Why does NSBatchDeleteRequest fail in unit tests?
NSBatchDeleteRequest requires an SQLite persistent store and fails on NSInMemoryStoreType. Switching your test store URL to /dev/null keeps the store in memory while using the SQLite engine, allowing batch requests to succeed.
Does NSBatchDeleteRequest trigger Core Data relationship delete rules?
Because NSBatchDeleteRequest operates directly on SQLite rows without loading objects into memory, it does not run NSManagedObject validation or prepareForDeletion() methods. If you need complex in-memory relationship cleanup or custom deletion hooks, fetch the objects with includesPropertyValues = false and delete them through the context.
Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.