skip to content

A Core Data Plant entity has a uniqueness constraint on speciesName, and saving a second plant of the same species fails with error 133021; why, and what fixes it?

level: seniorimportance: should knowfreq 48%

answer

  1. checked at save, not insert
  2. the default policy refuses
  3. NSConstraintConflict in the userInfo
  4. object trump turns insert into update
  5. defaults overwrite stored values too

basics

~10 s

Uniqueness constraints are enforced at save, and the default NSErrorMergePolicy refuses any conflict with NSManagedObjectConstraintMergeError (133021). Setting the context's mergePolicy to NSMergePolicy.mergeByPropertyObjectTrump turns the duplicate insert into an update of the existing row.

solid answer

~40 s

A constraint (the entity's **Constraints** field, `uniquenessConstraints = [["speciesName"]]` in code) is checked when the context saves, both among objects in the same save and against rows already in the store. Every context starts with `NSErrorMergePolicy`, so a conflict makes `save()` throw `NSManagedObjectConstraintMergeError` (133021) with `NSConstraintConflict` objects under `NSPersistentStoreSaveConflictsErrorKey`. If refusing is right, roll back and tell the user. For upsert, set `context.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump`: the stored row survives, takes the new object's values, and the inserted duplicate leaves the context. `mergeByPropertyStoreTrump` keeps the stored values instead. Watch the trap: a freshly inserted object carries its model defaults, so object trump overwrites a stored watering interval of 10 with the default 7.

code

swift · 24 lines
swift
import CoreData

func addPlant(species: String, nickname: String, in context: NSManagedObjectContext) {
    let plant = NSEntityDescription.insertNewObject(forEntityName: "Plant", into: context)
    plant.setValue(species, forKey: "speciesName")
    plant.setValue(nickname, forKey: "nickname")
    do {
        try context.save()
    } catch let error as NSError where error.code == NSManagedObjectConstraintMergeError {
        // Default NSErrorMergePolicy: the save is refused; inspect what collided.
        let conflicts = error.userInfo[NSPersistentStoreSaveConflictsErrorKey] as? [NSConstraintConflict] ?? []
        for conflict in conflicts {
            print("Violated \(conflict.constraint) with \(conflict.constraintValues)")
        }
        context.rollback()
    } catch {
        context.rollback()
    }
}

// Opting into upsert instead: the in-memory values win, property by property.
func configureForUpsert(_ context: NSManagedObjectContext) {
    context.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
}

go deeper

for a junior

Recall that a uniqueness constraint lists the attributes that must be unique, and that the check happens when the context saves.

for a middle

Explain the 133021 error, the NSConstraintConflict objects it carries, and how each merge policy resolves a duplicate.

for a senior

Use constraints for idempotent imports, set every known field so defaults do not overwrite data, and re-fetch the surviving object after save.

for a principal

Decide which entities carry a natural key, knowing each constraint costs save time and a migration to add after release.

## What a uniqueness constraint is A **uniqueness constraint** tells Core Data that no two objects of an entity may share a value, or a combination of values, for the listed attributes. In the model editor it is the entity's **Constraints** field; in code it is `NSEntityDescription.uniquenessConstraints`, an array of arrays: each inner array holds attribute names (or `NSAttributeDescription` objects) whose combined values must be unique. For the plant-care app: - `[["speciesName"]]` means one `Plant` per species; - `[["speciesName", "nickname"]]` would instead allow several plants of one species as long as their nicknames differ. The documentation adds two cautions. Constraint violations are expensive to handle, so it recommends **one uniqueness constraint per entity hierarchy**, which subentities may extend. And the constraint is part of the entity's **version hash**, so adding or changing one after release changes the schema the store was created with, a migration subject covered elsewhere. A store type that does not support constraints must refuse to open a model that has them; the SQLite store, the usual one on iOS, supports them. ## When the conflict is detected Nothing happens at insert. `Plant(context:)` with a duplicate species succeeds, and so does setting the property. The check runs during `save()`, in two situations the `NSConstraintConflict` header describes: 1. **Within one save**: two new objects in the same context share a species. The conflict has no database object and lists both conflicting objects. 2. **Against the store**: one object in the context matches a row already saved. The conflict carries that `databaseObject` and its snapshot. ## Why the save fails Every managed object context starts with **`NSErrorMergePolicy`**, the only policy that makes a conflict an error rather than resolving it. With a constraint violation, `save()` throws an `NSError` with code `NSManagedObjectConstraintMergeError` (133021). Its userInfo under `NSPersistentStoreSaveConflictsErrorKey` lists `NSConstraintConflict` objects, each with the violated `constraint`, the `constraintValues` and the `conflictingObjects`. Nothing is written, and the context still holds the unsaved duplicate until you roll back or fix it. ## Choosing a resolution | Policy | Result for a duplicate species | Use when | |---|---|---| | `NSErrorMergePolicy` (default) | save throws 133021 | a duplicate is a user mistake to report | | `NSMergePolicy.mergeByPropertyObjectTrump` | stored row kept, takes the in-memory values | an import or sync that upserts by key | | `NSMergePolicy.mergeByPropertyStoreTrump` | stored row kept with its stored values | the store's data must not be overwritten | With either trump policy the conflict becomes an **upsert**: the existing row keeps its identity, and the inserted duplicate is removed from the context, so its `managedObjectContext` is nil after the save. Code that kept a reference to the inserted object must re-fetch by species to find the surviving one. Within a single save, two new duplicates collapse to one row as well. ## The traps - **Defaults count as values.** A newly inserted object has a value for every attribute, including model defaults it never set explicitly. Under object trump those values win, so an import that only sets `speciesName` and `nickname` resets a stored `wateringInterval` of 10 to the default 7. Set every field the import knows, or fetch and update instead of inserting. - **The policy is per context.** A background import context and the view context each need the policy set; how contexts merge and resolve save conflicts in general is covered with managed object contexts. - **Nothing warns before save.** Because the check runs only inside `save()`, a fetch-before-insert check is still useful when the UI must say "you already have this species" before the user taps Save. ## An upsert import that behaves 1. Declare the natural key as the constraint (`speciesName`) and make that attribute non-optional. 2. Set `NSMergePolicy.mergeByPropertyObjectTrump` on the importing context before the first save. 3. Fill every attribute the import knows, so no model default overwrites real data. 4. After the save, re-fetch by key instead of using the objects you inserted. Used with an explicit policy, a constraint replaces the fetch-then-insert dance an import would otherwise need, and keeps duplicates out even when two code paths race to create the same species.

  • With mergeByPropertyObjectTrump, what happens to the duplicate Plant object your code inserted?
    It does not become a new row. The stored row survives with the new values, and the inserted object is removed from the context, so its `managedObjectContext` is nil after the save. Re-fetch by `speciesName` to work with the surviving object.
  • In Core Data, how does a two-attribute uniqueness constraint differ from two one-attribute constraints?
    `[["speciesName", "nickname"]]` makes the pair unique, so one species may appear with different nicknames. `[["speciesName"], ["nickname"]]` makes each attribute unique on its own, which is stricter and, by Apple's guidance, costlier, since it recommends one constraint per entity hierarchy.
  • Does a Core Data uniqueness constraint stop the duplicate at insert time?
    No. Insertion and assignment succeed; the conflict is detected only when the context saves. A form that must warn before saving needs its own fetch for an existing species.

  • Expecting the duplicate insert itself to throw
  • Assuming the default merge policy resolves constraint conflicts silently
  • Believing object trump inserts a second row for the duplicate species
  • Keeping a reference to the inserted duplicate after an upsert save
  • Forgetting that model defaults overwrite stored values under object trump