In Core Data, how do model versions and NSPersistentContainer's default store options let an app update add an attribute without losing data?
answer
- one .xcdatamodeld, several versions
- the store remembers its entity hashes
- two option keys, both on by default
- shouldMigrateStoreAutomatically and its partner
- error 134100 when migration is off
basics
~20 sAdd a new model version, make it current and never edit a shipped one. At load Core Data compares the store's version hashes with the current model, and NSPersistentContainer enables automatic migration and mapping inference by default, so an added optional attribute migrates.
solid answer
~40 sEvery schema change goes into a new version inside the `.xcdatamodeld`, which you then mark as the current version; shipped versions stay unchanged, because Core Data looks for the source model in the app's bundles. A store's metadata records the entity version hashes of the model that saved it. When `loadPersistentStores` finds hashes that don't match the current model, `shouldMigrateStoreAutomatically` lets Core Data migrate, and `shouldInferMappingModelAutomatically` lets it infer a mapping model when none is bundled. Both are `true` by default on every `NSPersistentStoreDescription`, so `NSPersistentContainer` runs a lightweight migration for an added optional attribute with no code. A coordinator you build yourself needs `NSMigratePersistentStoresAutomaticallyOption` and `NSInferMappingModelAutomaticallyOption` in its options, or the load fails with error 134100.
code
swift · 20 linesimport CoreData
// NSPersistentContainer: both flags already default to true on each description.
func makeContainer() -> NSPersistentContainer {
let container = NSPersistentContainer(name: "Records")
if let description = container.persistentStoreDescriptions.first {
print(description.shouldMigrateStoreAutomatically) // true
print(description.shouldInferMappingModelAutomatically) // true
}
return container
}
// A hand-built coordinator gets no migration unless you ask for it.
func addStore(to coordinator: NSPersistentStoreCoordinator, at storeURL: URL) throws {
let options: [AnyHashable: Any] = [
NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true
]
_ = try coordinator.addPersistentStore(type: .sqlite, at: storeURL, options: options)
}go deeper
Remember the routine: add a model version, edit the copy, mark it current, and never touch a version that has shipped.
Explain the mechanism: stored entity version hashes compared with the current model, then the migrate and infer switches, both true on NSPersistentStoreDescription by default.
Show you test upgrades with a store saved by the previous release, know which edits change the hash, and recognise error 134100 when automatic migration is off.
Frame model versions as a team contract: shipped versions are frozen, and each schema change in review states whether Core Data can infer it.
## What a model version is A Core Data **managed object model** describes the app's entities, attributes and relationships. In Xcode it lives in an `.xcdatamodeld` package, and that package can hold several **model versions**, one `.xcdatamodel` for each schema the app has shipped. Exactly one of them is the **current version**: the one `NSPersistentContainer` loads as the app's model. Changing the schema therefore means three steps: 1. Add a model version with Xcode's Add Model Version command, based on the current one. 2. Make the change in the copy. 3. Mark the copy as the current version. The older versions stay in the package, untouched. They describe the stores already sitting on users' devices, and Apple's documentation says that for an automatic migration Core Data must find both the source and the destination model at runtime, searching the app's bundles. ## How Core Data notices that a store is out of date A persistent store's metadata records the **entity version hashes** of the model that last saved it, under `NSStoreModelVersionHashes`. When the store is added, Core Data compares them with the current model's `entityVersionHashesByName`. The hashes cover only what affects how data is stored: | Changes the version hash | Does not change it | |---|---| | Entity name, superentity, abstract flag | A new default value | | Property name, optional, transient and read-only flags | A validation rule | | Attribute type | A fetch index | | Relationship destination, inverse, minimum and maximum count | | | Uniqueness constraints, a `versionHashModifier` | | So adding an attribute changes the hash, while setting a new default value does not; Apple's `NSManagedObjectModel` documentation says a model changed that way still opens the old stores. A `versionHashModifier` exists for the opposite case: forcing a new hash when the format of the stored data changed but the definition did not. ## The two switches Two settings decide what happens when the hashes differ. - **Migrate automatically.** `NSMigratePersistentStoresAutomaticallyOption` in a coordinator's options, or `shouldMigrateStoreAutomatically` on an `NSPersistentStoreDescription`. Core Data then looks for the source model and a mapping model in the app's bundles and migrates the store. - **Infer the mapping.** `NSInferMappingModelAutomaticallyOption`, or `shouldInferMappingModelAutomatically`. Combined with the first, Core Data builds an **inferred mapping model** if it cannot find a mapping model. That is a **lightweight migration**. Both description properties default to `true`, so a container made with `NSPersistentContainer(name:)` migrates a store after an added optional attribute without a line of migration code. A coordinator you build yourself starts with no options: pass both keys to `addPersistentStore(type:configuration:at:options:)`, or the out-of-date store is not migrated. ## What happens when migration is off With `shouldMigrateStoreAutomatically` set to `false`, Apple's documentation says loading an out-of-sync store produces an error. It is code 134100, `CocoaError.Code.persistentStoreIncompatibleVersionHash`, whose message says the model used to open the store is incompatible with the one used to create it. Apps turn automatic migration off on purpose when they want to run it themselves, for example to compare `metadataForPersistentStore(type:at:options:)` against the model with `isConfiguration(withName:compatibleWithStoreMetadata:)` first and show progress during a long migration. ## Deferring the expensive part (iOS 14) Some lightweight changes are costly on SQLite. The `NSPersistentStoreCoordinator` header explains that a transformation which drops a column, such as an entity losing an attribute or a relationship no longer needing its foreign key, requires copying the old table into a new one. Setting `NSPersistentStoreDeferredLightweightMigrationOptionKey` to `true` in the store options, available from iOS 14, lets Core Data delay that table copy. The store's metadata then carries the same key to signal the pending work, and the app finishes it at a time it chooses by calling `finishDeferredLightweightMigration()` on the coordinator. Only that table transformation is delayed. ## Mistakes that cost users their data - **Editing the shipped version in place.** A development build that deletes and recreates its store never notices. Users' stores were saved by a schema the bundle no longer contains, and the bundle is where Core Data is documented to look for a migration's source model. - **Deleting old versions** to tidy the package has the same effect for anyone still on those versions. - **Adding a non-optional attribute without a default value.** The existing rows have nothing to fill it with, and the migration fails validation. - **Testing only fresh installs.** A clean install never migrates; only a store saved by the previous release shows whether the update keeps its data. Lightweight migration covers many more changes than an added attribute, but each is still a new model version that Core Data compares by hash and migrates on load.
- In Core Data, does changing an attribute's default value need a new model version?Not for compatibility. A default value is not part of the version hash, so Apple's documentation says old stores still open, and no migration runs. Rows already saved keep their stored values; only objects inserted afterwards get the new default. Many teams still add a version for any model edit so the history stays readable, but Core Data does not require it.
- In Core Data, how can an app tell before loading whether a store needs migrating?Read the store's metadata with `NSPersistentStoreCoordinator.metadataForPersistentStore(type:at:options:)` and pass it to the current model's `isConfiguration(withName:compatibleWithStoreMetadata:)`. A `false` result means the hashes differ, so loading will migrate the store, or fail if automatic migration is off. Apps use the check to show a progress screen before a migration they expect to be slow.
- In Core Data, what does setting shouldMigrateStoreAutomatically to false change?An out-of-date store then fails to load with error 134100 instead of being migrated, as the property's documentation says. Teams do this when they drive migration themselves, for instance with `NSMigrationManager` and a progress indicator, and want the container never to start one on its own.
- Just edit the existing model version; Core Data adapts the store by itself.
- NSPersistentContainer needs both migration options set by hand before it migrates.
- Changing an attribute's default value makes old stores impossible to open.
- Delete old model versions once the new one is current; only the newest matters.
- Lightweight migration always needs a mapping model file you write in Xcode.