In Core Data, why does a viewContext save fail with error 133020 after a background import changed the same Expense, and which merge policy fits?
answer
- stale snapshot meets newer row
- the default refuses
- per property or whole object
- who wins: memory or store
basics
~10 s133020 is NSManagedObjectMergeError: viewContext edited an Expense whose stored row changed after it was loaded, and the default NSErrorMergePolicy refuses such saves. Setting NSMergePolicy.mergeByPropertyObjectTrump keeps the user's edited properties and the import's other changes.
solid answer
~40 sWhen a context saves a changed object, Core Data checks whether the store's row still matches the snapshot the context loaded. Here the import saved a new `amount` after `viewContext` loaded the expense, and the user then edited its `note`, so the save hit a conflict. The default `mergePolicy` is `NSErrorMergePolicy`, the only policy that hands the conflict back to you, as `NSManagedObjectMergeError`, code 133020 in `NSCocoaErrorDomain`. For a user-facing context I set `NSMergePolicy.mergeByPropertyObjectTrump`: it merges property by property, so the note the user typed wins and the import's amount stays. `overwrite` would push the stale amount back, and `rollback` would throw the note away. Turning on `automaticallyMergesChangesFromParent` makes the conflict rarer, because `viewContext` picks up the import's save before the user edits.
code
swift · 20 linesimport CoreData
@MainActor
func saveDashboardEdits(_ viewContext: NSManagedObjectContext) {
guard viewContext.hasChanges else { return }
do {
try viewContext.save()
} catch let error as NSError where error.domain == NSCocoaErrorDomain && error.code == NSManagedObjectMergeError {
// The default NSErrorMergePolicy refused the save: the store changed underneath.
print("merge conflict:", error.userInfo)
} catch {
print("save failed:", error)
}
}
@MainActor
func configure(_ viewContext: NSManagedObjectContext) {
viewContext.automaticallyMergesChangesFromParent = true
viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
}go deeper
Recall that a context's default merge policy makes a conflicting save throw, and that 133020 means another save changed the same object first.
Explain snapshots and conflicts, then the five policies: which merge per property, which replace the whole object, and how object-trump and store-trump differ.
Choose a policy per context from what must win, show why overwrite undoes imports, and add automatic merging to cut conflicts without relying on it alone.
Set the team default: which contexts keep the error policy, which use a property merge, and how conflicts are logged so a silent policy never hides a real data problem.
## What a save conflict is Each context remembers a **snapshot** of every object it loaded: the values the store had at that moment. Saving a changed or deleted object makes Core Data compare that snapshot with the current state at the coordinator and store. If someone else saved the same row in the meantime, the two disagree, and that is a **merge conflict**, represented by `NSMergeConflict`. The header notes that conflict detection is always performed on changed or deleted objects. In the expense app: 1. The dashboard's `viewContext` loads an `Expense` with `amount` 10. 2. The background import changes `amount` to 20 and saves. 3. Without a merge, `viewContext` still holds 10. The user edits `note` and taps Save. 4. The save fails with `NSManagedObjectMergeError` (code 133020, domain `NSCocoaErrorDomain`). ## Why it fails: the default policy A context's `mergePolicy` decides what happens on a conflict, and its documented default is `NSErrorMergePolicy`. Apple's documentation calls it the only policy that requires action to correct conflicts; the others make the save go through silently by following their own rule. With the default, the error identifies the conflicting objects and your code must refresh, reapply and save again. ## The five policies Each is a global constant from iOS 3 and, since iOS 10, a class property of `NSMergePolicy` (`.error`, `.mergeByPropertyObjectTrump` and so on). For the scenario above, with the user changing only `note`: | Policy | Rule | Stored amount / note | |---|---|---| | `NSErrorMergePolicy` (default) | fail the save | save throws 133020 | | `NSMergeByPropertyObjectTrumpMergePolicy` | merge per property; in-memory wins where both changed | 20 / user's note | | `NSMergeByPropertyStoreTrumpMergePolicy` | merge per property; store wins where both changed | 20 / user's note | | `NSOverwriteMergePolicy` | push the whole in-memory object | 10 / user's note: the import is undone | | `NSRollbackMergePolicy` | discard the in-memory object's changes | 20 / old note: the edit is lost | The two property policies differ only when both sides changed the **same** property: had the user also edited `amount`, object-trump keeps the user's value and store-trump keeps the import's. Each outcome follows from the policy's description in the Core Data headers. ## Choosing per context - **The UI context** usually takes `mergeByPropertyObjectTrump`: what the user just typed should win, and untouched properties keep the newer stored values. - **An import context** that refreshes server data might take `mergeByPropertyObjectTrump` too, so its fresh values win over what it loaded, or `mergeByPropertyStoreTrump` when the user's edits should beat the import. - **Keep `NSErrorMergePolicy`** where silently picking a winner is unacceptable and the code really handles the error. - **Avoid `overwrite`** on a context that may hold stale objects: it writes stale values back over newer ones. Setting a policy is one line: `viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump`. ## Fewer conflicts in the first place Setting `viewContext.automaticallyMergesChangesFromParent = true` makes `viewContext` merge saves made through its coordinator, so in the scenario the dashboard's expense already shows 20 before the user edits, and the save goes through even under the default policy. Conflicts still happen when the user edits during the import, so the policy is still needed. Merge policies also resolve conflicts with uniqueness constraints, covered with the managed object model, and deciding which of two devices' edits should win is a sync design question covered in the system design material on write conflicts. Here the subject is Core Data's own rule for one store and several contexts.
- If the default policy throws, how do you recover without a merge policy?Catch the error and call `refresh(_:mergeChanges:)` with `true` on each conflicting object: the documentation says it reloads the stored values, applies your local changes over them, and can resolve such a save failure. Then save again. The other policies do this kind of work for you by a fixed rule.
- Why can overwrite be dangerous on viewContext?`NSOverwriteMergePolicy` pushes the whole in-memory object to the store. If `viewContext` loaded the row before an import changed it, its stale values for untouched properties overwrite the import's newer ones, silently undoing the import for that row.
- Does automaticallyMergesChangesFromParent remove the need for a merge policy?No. It narrows the window by merging other contexts' saves into `viewContext`, but a conflict can still occur when an import saves between the user's edit and the user's save. The merge policy decides that case.
- The default merge policy keeps the most recent save automatically.
- NSOverwriteMergePolicy merges only the properties the user changed.
- A save conflict means the SQLite file is corrupt and must be rebuilt.
- Merge policies only matter when CloudKit or a server sync is involved.
- automaticallyMergesChangesFromParent makes save conflicts impossible.