skip to content

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%

answer

  1. shipped versions are read-only
  2. one model version per schema change
  3. a fixture store from each shipped version
  4. inference passing proves nothing about data
  5. deployment target decides staged or mapping

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.

solid answer

~50 s

I'd set four rules. First, a shipped `.xcdatamodel` version is never edited or deleted; every release that changes the schema adds exactly one version and makes it current. Second, model diffs get a checklist: a rename carries a renaming identifier, a new or newly mandatory attribute has a default, and a type change or a value moving between entities is flagged as custom work. Third, CI keeps a store saved by each shipped version, opens a copy with the current model and asserts values, because `inferredMappingModel` passing says nothing about data. Fourth, the tool for custom work follows the deployment target: from iOS 17, `NSStagedMigrationManager` with an ordered list covering every version, since it chains stages; below that, mapping models with `NSEntityMigrationPolicy`, each tied to one source and destination pair. What the app does when migration still fails is a product decision I'd make explicitly, not leave to a crash.

code

swift · 19 lines
swift
import CoreData

// One fixture per shipped model version, saved by that version's build.
func migrateFixture(named fixture: String, model: NSManagedObjectModel,
                    fixtures: URL, scratch: URL) throws -> NSPersistentContainer {
    let storeURL = scratch.appendingPathComponent("\(fixture).sqlite")
    for suffix in ["", "-wal", "-shm"] {          // SQLite keeps three files
        let source = fixtures.appendingPathComponent("\(fixture).sqlite\(suffix)")
        guard FileManager.default.fileExists(atPath: source.path) else { continue }
        try FileManager.default.copyItem(at: source,
            to: scratch.appendingPathComponent("\(fixture).sqlite\(suffix)"))
    }
    let container = NSPersistentContainer(name: "Records", managedObjectModel: model)
    container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: storeURL)]
    var loadError: Error?
    container.loadPersistentStores { _, error in loadError = error }
    if let loadError { throw loadError }
    return container
}

go deeper

for a junior

Know the basic rule behind all of this: never change a model version that has already shipped; add a new one.

for a middle

Explain why each rule exists: stored version hashes, bundle lookup of the source model, and changes inference cannot handle.

for a senior

Build the fixture-store tests per shipped version that assert values, and recognise review findings such as a rename without an identifier.

for a principal

Own the tooling choice: staged migration from iOS 17 against mapping models below it, the upkeep of the stage list, and the failure policy.

## The decision a lead owns A Core Data app that has shipped for years carries one store per user, saved by whatever model version that user last ran. Every migration Core Data performs starts from that store's version and ends at the current one. Keeping that path open for every user is not something one engineer remembers; it is a set of team rules, a test suite and a tooling choice. There is no single right answer for the tooling, which is what makes it a lead's call. ## Rules for the model package - **Shipped versions are frozen.** No edits and no deletions in a shipped `.xcdatamodel`. Its version hashes describe stores on real devices, and Core Data looks in the bundle for the source model when it migrates. - **One version per schema-changing release**, named after the release, and marked current in the same change. - **A review checklist for model diffs:** - a property or entity that disappears while another appears is a rename and needs a renaming identifier on the new version; - a new non-optional attribute, or one made non-optional, needs a default value, or a step that fills `nil` values before the change; - a change between unrelated types, a value split or combined, or a value moving into a new entity cannot be inferred correctly and is routed to custom migration work; - a change in what a stored value means, with no change to its definition, needs a `versionHashModifier` so Core Data sees a new version, plus custom code to convert the values. - **Uniqueness constraints count as schema.** They are part of the entity's version hash, and duplicates already in a user's store make the migration fail with a constraint violation, so they must be resolved first. ## Proving it in CI 1. Keep one **fixture store** per shipped version, saved by that version's build with realistic rows, including the `nil` values and duplicates real users have. Copy the `-wal` and `-shm` files with the `.sqlite`, or checkpoint the database into a single file before saving the fixture. 2. For each fixture, copy it to a temporary directory, load it with the current model through the same container setup the app uses, and assert specific values. 3. Also call `NSMappingModel.inferredMappingModel(forSourceModel:destinationModel:)` for each new version pair. Treat it as a quick check that the shape is inferable, not as proof: a rename without an identifier passes it. ## Recording each version Keep a small table in the repository, updated in the same change as the model: | Release | Model version | Version checksum | Migration from the previous version | |---|---|---|---| | 1.0 | Records | recorded | none | | 2.0 | Records 2 | recorded | lightweight | | 3.0 | Records 3 | recorded | staged, through Records 3a | The checksum comes from the model's `versionChecksum` property, the version's `VersionInfo.plist` or Xcode's build log, and staged migration's `NSManagedObjectModelReference` needs exactly that value. The table also tells a reviewer which versions still need a fixture store, and which intermediate versions exist only to make a migration possible. ## Staged migration or mapping models | Question | Staged migration | Mapping model with a policy | |---|---|---| | Minimum deployment | iOS 17 | any supported release | | Unit of custom work | handlers before and after a stage | per-object code in an entity mapping | | Multiple versions behind | stages run in order through each version | Core Data looks for a mapping from the store's version straight to the current one | | Upkeep | a stage list naming every version, with checksums | one mapping model per source and destination pair, regenerated if either changes | For a team deploying to iOS 17 or later, staged migration is usually the better default: intermediate versions keep each step lightweight, and the stage list chains a store from any shipped version. The cost is the list itself. The `NSPersistentStoreStagedMigrationManagerOptionKey` header requires a total ordering of the models, so every lightweight version must appear in an `NSLightweightMigrationStage`, and a forgotten version is a bug for the users still on it. ## When a migration still fails - `loadPersistentStores` reports the error to its completion handler; an app that calls `fatalError` there crashes on every launch for that user. - Keep the store file, record the error with the store's model version, and decide in advance what the app shows. - Whether the app may delete the store and resync from a server, and how far back the app supports skipped releases, are product decisions covered in the system design material on on-device migrations; Core Data supplies the error, not the policy. The rules cost little per release. Skipping them shows up years later, on a device whose owner skipped six updates.

  • In Core Data, why should a migration test copy the fixture's -wal and -shm files as well?
    Apple's documentation says Core Data creates SQLite stores in write-ahead logging mode by default and appends transactions to a `.sqlite-wal` file beside the store, until a checkpoint moves them into the main file. Copying only the `.sqlite` can give the test an older or incomplete database, so it migrates data that never matches what users have. Copy all three, or produce the fixture as a single checkpointed file.
  • In Core Data, how would you migrate users several versions behind with mapping models instead of staged migration?
    Automatic migration looks for one mapping model from the store's version to the current one, so either ship a mapping for every older version, or run the steps yourself: read the store's metadata, find its version, and run `NSMigrationManager` one version at a time to the current model. Staged migration on iOS 17 does that chaining for you.

  • Once most users have updated, old model versions can be deleted from the bundle.
  • A test that calls inferredMappingModel for each version pair proves migration is safe.
  • Staged migration only needs stages for the versions with custom handlers.
  • Core Data chains mapping models across versions automatically.
  • Calling fatalError when loadPersistentStores fails is fine because migrations are tested.

Assumes a deployment target of iOS 17 or later for staged migration (NSStagedMigrationManager is iOS 17); mapping models and NSEntityMigrationPolicy cover earlier releases. Checked against the iOS 27.1 SDK.