In Core Data, after an NSBatchDeleteRequest removes old expenses, why does the dashboard still show them, and how do you make viewContext see the change?
answer
- below the context, in the store
- no save notification
- ask for object IDs back
- merge them by hand
basics
~20 sBatch requests change rows in the store without loading objects or saving a context, so viewContext gets nothing to merge. Set resultType to return object IDs and pass them to NSManagedObjectContext.mergeChanges(fromRemoteContextSave:into:), or consume persistent history.
solid answer
~40 s`NSBatchDeleteRequest`, `NSBatchUpdateRequest` and `NSBatchInsertRequest` run through `execute(_:)` and work at the store level, so they never load managed objects and never produce a context save. That is what makes a 40,000-row import or purge fast, and also why `viewContext` keeps showing deleted rows even with `automaticallyMergesChangesFromParent` on: that setting merges saves, and there was none. I set the request's `resultType` to return object IDs (`.resultTypeObjectIDs` for a delete), read them from the result, and call `NSManagedObjectContext.mergeChanges(fromRemoteContextSave:into:)` with `NSDeletedObjectsKey` and `viewContext`. The alternative is persistent history tracking, which records batch changes too. Batch delete needs a SQLite store, and the Deny delete rule is not compatible with it.
code
swift · 20 linesimport CoreData
func deleteExpenses(before cutoff: Date, in container: NSPersistentContainer) async throws {
let context = container.newBackgroundContext()
let deletedIDs: [NSManagedObjectID] = try await context.perform {
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Expense")
fetch.predicate = NSPredicate(format: "date < %@", cutoff as NSDate)
let request = NSBatchDeleteRequest(fetchRequest: fetch)
request.resultType = .resultTypeObjectIDs
let result = try context.execute(request) as? NSBatchDeleteResult
return result?.result as? [NSManagedObjectID] ?? []
}
let viewContext = container.viewContext
await viewContext.perform {
NSManagedObjectContext.mergeChanges(
fromRemoteContextSave: [NSDeletedObjectsKey: deletedIDs],
into: [viewContext]
)
}
}go deeper
Recall that batch requests change many rows without loading objects, and that the screen will not notice them by itself.
Explain the three batch request types, how execute(_:) runs them in the store, and why no save notification follows.
Fix the stale dashboard with object-ID result types and mergeChanges(fromRemoteContextSave:into:), and know the validation and Deny limits before choosing a batch request.
Decide when batch requests are allowed and how their changes reach the UI everywhere, by a merge helper or by persistent history, so no screen goes stale.
## What makes a batch request different A normal delete fetches every object into a context, calls `delete(_:)` on each and saves, which for 40,000 rows means 40,000 objects in memory. **Batch requests** skip the context: you describe the change, call `execute(_:)` on a context, and the work happens in the persistent store. | Request | Since | Describes the change with | Result type default | |---|---|---|---| | `NSBatchInsertRequest` | iOS 13 | an array of dictionaries, or from iOS 14 a `dictionaryHandler` or `managedObjectHandler` closure | status only | | `NSBatchUpdateRequest` | iOS 8 | `predicate` plus `propertiesToUpdate` (constants or `NSExpression` values) | status only | | `NSBatchDeleteRequest` | iOS 9 | an `NSFetchRequest`, or an array of object IDs of one entity | status only | Apple's documentation describes the batch delete as working "at the SQL level of the persistent store" and as available only with a SQLite store. ## Why the dashboard is stale Contexts learn about other contexts' work through **saves**. A background context's `save()` posts a did-save notification, and `automaticallyMergesChangesFromParent` or `mergeChanges(fromContextDidSave:)` consume it. A batch request saves no context, so there is nothing to consume. Apple's documentation is explicit on both sides: - the batch delete page: the context "doesn't automatically merge a request's deletions because they happen at the SQL level"; - the persistent history article: an import done through a batch operation "doesn't generate an NSManagedObjectContextDidSave notification, and the view misses these relevant updates." So `viewContext` keeps its registered expenses, a fetched results controller keeps its rows, and the totals stay wrong until something tells the context. ## Merging the result by hand 1. Ask for identifiers: `request.resultType = .resultTypeObjectIDs` for a delete, `.objectIDs` for an insert, `.updatedObjectIDsResultType` for an update. 2. Execute on a background context inside `perform`, and cast the result to `NSBatchDeleteResult`, `NSBatchInsertResult` or `NSBatchUpdateResult`; its `result` is an array of `NSManagedObjectID`. 3. Call the class method `NSManagedObjectContext.mergeChanges(fromRemoteContextSave:into:)` with a dictionary keyed by `NSDeletedObjectsKey`, `NSInsertedObjectsKey` or `NSUpdatedObjectsKey`, and the contexts to update, usually `[viewContext]`, on the context's queue. Its documentation says it merges efficiently into several contexts, nested ones included. After the merge, `viewContext` treats those objects as deleted, inserted or refreshed, so observers of that context, such as a fetched results controller, can update. ## The alternative: persistent history When batch work happens in many places, or in an app extension, persistent history tracking records every store transaction, batch ones included, and lets each context fetch and merge what changed since it last looked. Enabling it is a store option, covered with the persistent stack setup. ## Rules batch requests do not enforce - **Validation.** Requests run below the context, so the documentation tells you to make sure a batch delete does not break model validation rules beyond basic delete rules, such as a relationship's minimum count. - **Deny.** The Deny delete rule is not compatible with `NSBatchDeleteRequest`. - **One entity at a time.** A batch delete built from object IDs must name objects of one entity type; mixing types is an error. - **Handlers finish on true.** An insert's `dictionaryHandler` is called repeatedly until it returns `true`; returning `false` asks for another row. ## When to use one Batch requests fit the statement import's bulk insert, a purge of last year's expenses or a one-column fix across thousands of rows. Use a normal context when the change needs validation, change-tracking side effects in the context or per-object logic, or when only a few dozen rows change.
- Which model rules can an NSBatchDeleteRequest break?Apple's documentation asks you to make sure a batch delete does not violate validation rules beyond basic delete rules, such as dropping a relationship below its minimum count, and says the Deny delete rule is not compatible with it. When a delete must respect Deny or full validation, delete through a context and save instead.
- Why does the dashboard update after a normal background save but not after a batch insert?A normal save posts a did-save notification that automatic merging or `mergeChanges(fromContextDidSave:)` consumes. A batch insert writes rows without saving a context, so no notification exists; you merge the returned IDs yourself or read persistent history.
- When is persistent history a better fit than merging the returned IDs?When batch writes come from several places, or from another process such as an extension, so no single call site can merge them. History records every transaction, and each context processes what it missed. For one import screen, merging its own IDs is simpler.
- automaticallyMergesChangesFromParent also picks up batch deletes and updates.
- A batch delete loads the objects and deletes them one by one.
- Calling viewContext.save() after the batch request refreshes the dashboard.
- Batch requests run the model's validation and every delete rule like a normal save.
- NSBatchDeleteRequest works the same on an in-memory store as on SQLite.