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?
answer
- each handler sees one schema
- will runs before, did runs after
- an intermediate model version
- references carry a versionChecksum
- NSPersistentStoreStagedMigrationManagerOptionKey
basics
~20 sA 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.
solid answer
~40 sStaged migration, new in iOS 17, splits a change lightweight migration cannot express into stages that `NSStagedMigrationManager` applies in order. An `NSCustomMigrationStage(migratingFrom:to:)` joins two `NSManagedObjectModelReference`s and offers `willMigrateHandler`, run just before the store's schema migrates, and `didMigrateHandler`, run just after; in both, the manager's `container` gives access to the migrating store. Going straight from version 2 to 3 cannot keep the data: before the stage the store has no `Artist` entity, and after it `artistName` is gone. So add a version 3a that has both, migrate 2 to 3a, create the artists in that stage's `didMigrateHandler` with a background context and key-value coding, then migrate 3a to 3 to drop the string. Pass the manager in the store description with `setOption(_:forKey:)` under `NSPersistentStoreStagedMigrationManagerOptionKey`.
code
swift · 38 linesimport CoreData
func stagedManager(v2: NSManagedObjectModel, v3a: NSManagedObjectModel,
v3: NSManagedObjectModel) -> NSStagedMigrationManager {
let ref2 = NSManagedObjectModelReference(model: v2, versionChecksum: v2.versionChecksum)
let ref3a = NSManagedObjectModelReference(model: v3a, versionChecksum: v3a.versionChecksum)
let ref3 = NSManagedObjectModelReference(model: v3, versionChecksum: v3.versionChecksum)
// Stage 1: add Artist and the relationship, keep artistName; then fill Artist.
let addArtist = NSCustomMigrationStage(migratingFrom: ref2, to: ref3a)
addArtist.label = "V2 to V3a: add Artist"
addArtist.didMigrateHandler = { manager, _ in
guard let container = manager.container else { return }
let context = container.newBackgroundContext()
try context.performAndWait {
var artists: [String: NSManagedObject] = [:]
for album in try context.fetch(NSFetchRequest<NSManagedObject>(entityName: "Album")) {
guard let name = album.value(forKey: "artistName") as? String else { continue }
let artist = artists[name]
?? NSEntityDescription.insertNewObject(forEntityName: "Artist", into: context)
artist.setValue(name, forKey: "name")
artists[name] = artist
album.setValue(artist, forKey: "artist")
}
try context.save()
}
}
// Stage 2: drop artistName now that every album points at an Artist.
let dropString = NSCustomMigrationStage(migratingFrom: ref3a, to: ref3)
dropString.label = "V3a to V3: drop artistName"
return NSStagedMigrationManager([addArtist, dropString])
}
func describe(storeURL: URL, manager: NSStagedMigrationManager) -> NSPersistentStoreDescription {
let description = NSPersistentStoreDescription(url: storeURL)
description.setOption(manager, forKey: NSPersistentStoreStagedMigrationManagerOptionKey)
return description
}go deeper
Know that iOS 17 added staged migration for changes lightweight migration cannot infer, with handlers before and after each step.
Explain what willMigrateHandler and didMigrateHandler each see, and how references and checksums identify the versions.
Decompose a change into an intermediate version, write handlers with key-value coding, and know a failed didMigrateHandler leaves the store migrated.
Treat the stage list as a maintained artifact: every shipped version appears in order, and each data step is safe to redo.
## What staged migration adds Lightweight migration infers a mapping but cannot run code. **Staged migration**, added in iOS 17, keeps every schema step lightweight and gives you hooks around each step. Apple's documentation describes it as reducing an incompatible migration to a series of compatible stages, with a chance to prepare the store before each stage and clean up after it. ## The pieces | Type | Role | |---|---| | `NSStagedMigrationManager` | holds the ordered `stages`, runs them, and exposes the migrating store through `container` | | `NSCustomMigrationStage` | one step from `currentModel` to `nextModel`, with optional `willMigrateHandler` and `didMigrateHandler` | | `NSLightweightMigrationStage` | a run of versions that needed no decomposition, identified by `versionChecksums` | | `NSManagedObjectModelReference` | a promise of one model version, checked against its `versionChecksum` | | `NSPersistentStoreStagedMigrationManagerOptionKey` | the store option that hands the manager to Core Data | A model's checksum comes from its `versionChecksum` property, the versioned model's `VersionInfo.plist`, or Xcode's build log. ## Why one custom stage is not enough A record-collection app's version 3 replaces `Album.artistName` with a relationship to a new `Artist` entity. A single stage from version 2 to version 3 gives you two moments: 1. **`willMigrateHandler`** runs immediately before the store's schema migrates. The store still has version 2's shape: `artistName` is there, `Artist` is not, so there is nowhere to put the artists. 2. The schema step itself, which is lightweight: it removes `artistName` and adds the entity and relationship. 3. **`didMigrateHandler`** runs immediately after. Now `Artist` exists, but the strings were removed in step 2. Neither handler sees both the old strings and the new entity, which is the whole job. ## Decomposing version 2 to version 3 1. Add an **intermediate model version**, 3a: version 2 plus the `Artist` entity and the optional `artist` relationship, still keeping `artistName`. From 2 to 3a is purely additive, so it is lightweight. 2. Stage one, from 2 to 3a: in its `didMigrateHandler`, open a background context from `migrationManager.container`, fetch every album, find or create one `Artist` per distinct name, link it, and save. 3. Stage two, from 3a to 3: drop `artistName`. It needs no handler. 4. Ship 3 as the current version, with 3a kept in the bundle beside the others. ## Writing the handlers - Use `NSManagedObject` with `value(forKey:)` and `setValue(_:forKey:)`. Your generated classes describe the final model, not the intermediate one the container is using. - Work inside `perform` or `performAndWait` on a context from the manager's `container`, and save before returning. - Throwing from a handler reports that error to the load's completion handler. A `didMigrateHandler` runs after its schema step, so a throw there does not put the store back: it stays at the stage's destination version, and the next launch does not run that stage again. Make the data step safe to redo from the app if it can fail halfway. - Give each stage a `label`; the header says it is available when reading the store's persistent history. ## How Core Data picks the stages to run The store option's header says custom stages are applied in their order at the appropriate time, when the store's model matches the stage's model references. A store saved at version 2 therefore runs both stages, a store already at 3a starts at the second, and a store at 3 runs none. The same rule explains why a stage whose `didMigrateHandler` failed is not retried: once its schema step has run, the store no longer matches that stage's `currentModel`. Lightweight stages fill the ordering between custom ones, so stores from versions that needed no decomposition still have a described path to the next custom stage. ## Rules for the stage list - Core Data processes stages in the order given, and the store option's header says the list must be a total ordering of every model version the store may need. - Every version that migrates lightweight must still appear, in one or more `NSLightweightMigrationStage`s. - The stage classes and the option key need iOS 17; an app deploying earlier needs a mapping model or a migration it runs itself for the same change. The pattern generalises: whenever old and new data must both exist for code to convert one into the other, give them a model version where they coexist.
- In Core Data's staged migration, when would you put work in willMigrateHandler instead of didMigrateHandler?When the next schema step would fail or lose data unless the store is prepared first. Apple's example is making an optional attribute non-optional: in `willMigrateHandler` the store still has the old shape, so you can set every `nil` to a real value before the lightweight step makes the attribute mandatory. Work that needs the new entities belongs in `didMigrateHandler`.
- In Core Data's staged migration, where does an NSManagedObjectModelReference's checksum come from?From the model's `versionChecksum` property, a Base64-encoded 128-bit version hash, or from the versioned model's `VersionInfo.plist` or Xcode's build log. The reference is a promise that Core Data fulfils during migration, and the checksum lets it verify that the model it resolves is the version you meant. Editing that version's schema afterwards changes the checksum.
Moving house with a single handover day fails if you may only pack before returning the old keys and only unpack after getting the new ones: the furniture has nowhere to be in between. Overlapping the two leases for a week, when both homes are yours, is the intermediate model version.
- One custom stage's willMigrateHandler can copy the strings into the new Artist entity.
- Staged migration works on any iOS release that has NSPersistentContainer.
- Only versions that need handlers have to be listed among the stages.
- Use the generated Album and Artist classes inside the migration handlers.
- A didMigrateHandler that throws rolls the store back to the previous version.
Assumes iOS 17 or later: NSStagedMigrationManager, both stage classes and NSManagedObjectModelReference arrived in iOS 17; checked against the iOS 27.1 SDK.