skip to content

Migrations & Versioning

Lightweight migration covers changes Core Data can infer; others need a mapping model or a staged plan. Interviewers ask what makes a change non-inferable and how an update avoids losing user data.

on this pageshow

explore

questions

6

In Core Data, how do model versions and NSPersistentContainer's default store options let an app update add an attribute without losing data?

level: middleimportance: must knowfreq 60%

answer

  1. one .xcdatamodeld, several versions
  2. the store remembers its entity hashes
  3. two option keys, both on by default
  4. shouldMigrateStoreAutomatically and its partner
  5. error 134100 when migration is off

basics

~20 s

Add 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 s

Every 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 lines
swift
import 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

for a junior

Remember the routine: add a model version, edit the copy, mark it current, and never touch a version that has shipped.

for a middle

Explain the mechanism: stored entity version hashes compared with the current model, then the migrate and infer switches, both true on NSPersistentStoreDescription by default.

for a senior

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.

for a principal

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.
open as a page

In Core Data, version 2 renames Album's title attribute to name; why do titles vanish after lightweight migration, and how does a renaming identifier keep them?

level: middleimportance: should knowfreq 48%

basics

~20 s

An inferred mapping pairs attributes by name, so a renamed attribute looks like one removed and one added: migration succeeds and the values are dropped. Setting the new attribute's renaming identifier to its old name makes Core Data copy them across.

open as a page

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?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Lightweight 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.

open as a page

In Core Data on iOS 17 or later, why can one NSCustomMigrationStage not move Album's artist string into a new Artist entity, and how do staged stages fix it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

A custom stage's willMigrateHandler runs before the schema changes, when Artist does not exist, and its didMigrateHandler runs after, when artistName is gone. Add an intermediate version holding both, fill Artist in that stage's didMigrateHandler, then drop the string in a second stage.

open as a page

As the lead of a Core Data app with many shipped model versions, which rules keep every version migratable, and when would you adopt staged migration?

level: principalimportance: should knowfreq 30%

basics

~20 s

Freeze shipped model versions, add one version per schema change, review renames, new mandatory attributes and moved values, and test saved stores from each shipped version. Adopt staged migration once the deployment target is iOS 17; below it, mapping models carry custom steps.

open as a page

In Core Data, how does a mapping model with an NSEntityMigrationPolicy subclass turn each album's free-text artist into a shared Artist entity during migration?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

Add a mapping model from version 2 to version 3 and set the Album entity mapping's custom policy to an NSEntityMigrationPolicy subclass. Its createDestinationInstances(forSource:in:manager:) calls super, then finds or creates the matching Artist and links the new album to it.

open as a page