In Core Data, which model changes can lightweight migration infer, which make it fail at launch, and which does it accept while silently losing data?
answer
- three outcomes, not two
- Apple's list of obvious patterns
- unrelated types have no inferred mapping
- a mandatory attribute meets nil rows
- moving a value into a new entity
basics
~20 sLightweight migration infers added, removed and renamed entities, attributes and relationships, plus optionality changes with a default. A String-to-number change or a mandatory attribute with nil rows fails the load; moving a string into a new entity is inferred and loses the data.
solid answer
~50 sApple lists the inferable patterns: adding or removing an attribute, making an attribute optional, making one non-optional with a default value, renaming with a renaming identifier, adding or removing relationships, to-one to to-many, unordered to ordered and back, and most hierarchy changes except merging hierarchies. Two kinds of change fail at load. Changing `year` from String to Integer 16 has no inferred mapping, so loading fails with 134140, missing mapping model, over an underlying 134190 that says the attribute types are incompatible. A non-optional attribute without a default fails validation, 134110, as soon as one row is `nil`. The third kind is accepted: replacing the free-text `artistName` with an `Artist` entity reads as one attribute removed and one relationship added, so migration succeeds and every album loses its artist. `inferredMappingModel(forSourceModel:destinationModel:)` tells you a mapping can be inferred, never that data survives.
code
swift · 13 linesimport CoreData
// Ask Core Data whether it can infer a mapping, without migrating anything.
func canInfer(from source: NSManagedObjectModel, to destination: NSManagedObjectModel) -> Bool {
do {
_ = try NSMappingModel.inferredMappingModel(forSourceModel: source,
destinationModel: destination)
return true // inferable, which says nothing about whether data survives
} catch {
print((error as NSError).code, (error as NSError).userInfo["reason"] ?? "")
return false
}
}go deeper
Recall the simple inferable changes: add or remove an attribute, make one optional, rename with a renaming identifier.
Explain why a String to number change has no inferred mapping and why a non-optional attribute needs a default for existing rows.
Spot the silent cases, such as a string moved into a new entity, and prove a change with a fixture store that checks values, not loads.
Set the rule that every model change is classified as inferable, failing or lossy in review, with the lossy ones routed to custom migration code.
## What lightweight migration is A **lightweight migration** is Core Data's automatic migration with an **inferred mapping model**: instead of reading a mapping model you wrote, Core Data compares the source and destination model versions and derives the mapping itself. Apple's documentation says this works when the changes fit an obvious migration pattern. Knowing where that line runs matters because a change can land in one of three places: inferred and correct, refused at load, or inferred and wrong. ## Changes Core Data infers Apple's lightweight migration documentation lists these patterns: - adding or removing an attribute; - making a non-optional attribute optional; - making an optional attribute non-optional **and** giving it a default value; - renaming an entity, attribute or relationship through a **renaming identifier**; - adding or removing a relationship, changing a to-one into a to-many, or an unordered to-many into an ordered one and back; - adding, removing and renaming entities in a hierarchy, and moving properties up or down it, but not merging two hierarchies that had no common parent. Core Data also migrates a widened number type, such as Integer 16 to Integer 32 or Float to Double, with its values. Cover any type change with a fixture test anyway. ## Changes that fail at load | Change | What loading reports | |---|---| | `year` changes from String to Integer 16 | 134140, missing mapping model, over 134190: source and destination attribute types are incompatible | | An optional attribute becomes non-optional with no default, and some rows are `nil` | 134110, migration error: missing attribute values on a mandatory destination attribute | | A new non-optional attribute with no default | 134110 for the same reason, because every existing row lacks a value | The second row is worth noticing: `inferredMappingModel(forSourceModel:destinationModel:)` still returns a mapping for it, because the problem is in the data, not the schema. The load fails only on a store that actually holds a `nil`, so a test store full of complete rows passes while a real user's store does not. ## Changes accepted while data is lost These are the dangerous ones, because nothing fails: 1. **A rename without a renaming identifier.** Inference sees one property removed and another added, and the values are dropped. 2. **Moving a value into a new entity.** A record-collection app's version 3 replaces `Album.artistName` with a to-one `artist` relationship to a new `Artist` entity shared by albums. To inference that is an attribute removed, an entity added and a relationship added, all inferable. The store opens, there are no artists, and every album's relationship is empty. 3. **Splitting or combining values.** Any change where new values must be computed from old ones has no inferable pattern: inference carries values across, drops them or applies a default, but never derives them from other values. ## Reading the errors The codes are declared in Core Data's error header, and Swift exposes them on `CocoaError.Code`: | Code | Swift name | Meaning | |---|---|---| | 134100 | `persistentStoreIncompatibleVersionHash` | the store's entity version hashes do not match the model | | 134110 | `migration` | a general migration error; validation details sit in the underlying error | | 134130 | `migrationMissingSourceModel` | no model matching the store could be found | | 134140 | `migrationMissingMappingModel` | no mapping model was found and none could be inferred | | 134190 | `inferredMappingModel` | creating an inferred mapping model failed | For 134140 the top-level reason reads "Can't find or automatically infer mapping model for migration", and the underlying 134190 names the entity, the property and the cause, so log the whole `userInfo`, not just the code. ## Probing before you ship - Call `NSMappingModel.inferredMappingModel(forSourceModel:destinationModel:)` in a test for each new version. If it throws, the change needs more than inference; if it returns, the shape is inferable and nothing more is proven. - Keep a store saved by the previous release, with realistic rows including `nil` values, and open it with the new model. Assert the values, not just a successful load. - Read the model diff for properties that vanish while others appear. ## When inference is not enough Non-inferable work has two homes in Core Data. A **mapping model** with an `NSEntityMigrationPolicy` subclass lets code run for each object during a migration between two specific versions. On iOS 17 and later, **staged migration** with `NSStagedMigrationManager` splits the change into stages, each lightweight, with handlers that run before and after a stage to prepare or fix up the data. Either way the artist strings become `Artist` objects because code you wrote made them, which is exactly what inference cannot do.
- In Core Data, why can a migration that passed every test still fail for some users with error 134110?Because the failure depends on the data. An attribute made non-optional without a default migrates any store whose rows all hold a value, and fails validation on a store with even one `nil`. Test fixtures built by hand are often complete; real stores are not. Seed the fixtures with the gaps real users have, or give the attribute a default.
- In Core Data, can lightweight migration give two existing entities a new common parent entity?No. Apple's documentation says lightweight migration can add, remove and rename entities in a hierarchy and move properties up and down it, but cannot merge hierarchies: two entities that share no parent in the source cannot share one in the destination. That change needs custom migration work, such as a mapping model or staged migration with an intermediate version.
- If lightweight migration cannot handle a change, the app always crashes at launch.
- inferredMappingModel returning a model proves the migration keeps all data.
- Lightweight migration converts a String attribute to a number by parsing each value.
- Adding an entity and a relationship is unsafe for lightweight migration.
- An attribute can become non-optional without a default if rows usually have values.