skip to content

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%

answer

  1. a mapping model for one version pair
  2. Custom Policy on the entity mapping
  3. create, relate, validate
  4. call super, then find or create
  5. module-qualified class name or @objc

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.

solid answer

~40 s

Inference would drop the string, so you give Core Data a **mapping model**: create one in Xcode with version 2 as the source and version 3 as the destination, and on the `Album` entity mapping set the custom policy to your `NSEntityMigrationPolicy` subclass. Automatic migration uses a bundled mapping model when one matches the store's model and the current model, and infers only when none does. The migration manager takes each entity mapping through three passes: create instances, create relationships, validate. In `createDestinationInstances(forSource:in:manager:)`, call `super` so the album is created and associated with its source, look it up with `destinationInstances(forEntityMappingName:sourceInstances:)`, then fetch or insert the `Artist` in `manager.destinationContext` and set the relationship. Give the class an `@objc` name or enter its module-qualified name, or the policy cannot be found and the migration fails.

code

swift · 27 lines
swift
import CoreData

@objc(AlbumArtistMigrationPolicy)
final class AlbumArtistMigrationPolicy: NSEntityMigrationPolicy {
    override func createDestinationInstances(
        forSource source: NSManagedObject,
        in mapping: NSEntityMapping,
        manager: NSMigrationManager
    ) throws {
        // Default behaviour: create the Album and associate it with its source.
        try super.createDestinationInstances(forSource: source, in: mapping, manager: manager)
        guard let name = source.value(forKey: "artistName") as? String,
              let album = manager.destinationInstances(
                  forEntityMappingName: mapping.name, sourceInstances: [source]).first
        else { return }

        // Find or create one Artist per distinct name in the new store.
        let context = manager.destinationContext
        let request = NSFetchRequest<NSManagedObject>(entityName: "Artist")
        request.predicate = NSPredicate(format: "name == %@", name)
        request.fetchLimit = 1
        let artist = try context.fetch(request).first
            ?? NSEntityDescription.insertNewObject(forEntityName: "Artist", into: context)
        artist.setValue(name, forKey: "name")
        album.setValue(artist, forKey: "artist")
    }
}

go deeper

for a junior

Know that a mapping model exists for changes inference cannot handle, and that a policy class adds code to it.

for a middle

Describe the three passes, create, relate, validate, and where createDestinationInstances fits among them.

for a senior

Show the details that break in production: call super or associate, the module-qualified class name, and usesStoreSpecificMigrationManager on a manual run.

for a principal

Weigh mapping models against staged migration: mapping models suit apps deploying below iOS 17, but each is tied to one version pair.

## Why a mapping model is needed A record-collection app's version 3 turns `Album.artistName`, a free-text string, into a to-one `artist` relationship to a new `Artist` entity shared by many albums. Lightweight migration accepts the change and drops every string, because inference cannot compute new objects from old values. A **mapping model** is the Core Data file that describes a migration between two specific model versions: one **entity mapping** per destination entity, with **property mappings** that say where each value comes from. An entity mapping can name an **entity migration policy**, an `NSEntityMigrationPolicy` subclass whose methods run during that mapping, and that is where code turns strings into objects. ## Wiring it up 1. Create a mapping model in Xcode with version 2 as the source and version 3 as the destination, and check the entity and property mappings it starts with. 2. Select the `Album` entity mapping and set its custom policy to the policy class. That field is the entity mapping's `entityMigrationPolicyClassName`, which Apple's documentation says you typically set in the mapping model editor. 3. Write the class with an `@objc` name, or enter the module-qualified name such as `Records.AlbumArtistMigrationPolicy`. A bare Swift class name does not resolve, and the migration fails. 4. Leave automatic migration on. Core Data looks for a mapping model matching the store's model and the current model, and infers one only when it finds none. A mapping model records the version information of its source and destination entities, so editing either model version afterwards means regenerating it. ## The policy's life cycle `NSMigrationManager` processes each entity mapping in three passes: create the destination objects, create their relationships, validate. The policy's methods mark those points. | Method | When the manager calls it | |---|---| | `begin(_:with:)` | at the start of the entity mapping | | `createDestinationInstances(forSource:in:manager:)` | once per source object | | `endInstanceCreation(forMapping:manager:)` | when the creation pass ends | | `createRelationships(forDestination:in:manager:)` | once per destination object | | `endRelationshipCreation(forMapping:manager:)` | when the relationship pass ends | | `performCustomValidation(forMapping:manager:)` | during validation | | `end(_:manager:)` | at the end of the entity mapping | ## Writing createDestinationInstances - **Call `super` first.** The default implementation creates the album from the property mappings and calls `associate(sourceInstance:withDestinationInstance:for:)`. The header warns that an override which skips `super` must make that association itself, or later passes cannot find the object. - **Find the new album** with `manager.destinationInstances(forEntityMappingName:sourceInstances:)`. - **Find or create the artist** in `manager.destinationContext`, the context writing the new store. A fetch with a predicate on `name` sees artists inserted earlier in the same migration, so each name produces one `Artist`. - **Use key-value coding** (`value(forKey:)`, `setValue(_:forKey:)`) on these objects; the source object belongs to the old model, which your current generated classes do not describe. If `Artist` objects came from their own entity mapping instead, the linking would belong in `createRelationships(forDestination:in:manager:)`, which runs only after every object of the creation pass exists, using the manager's association lookups. ## What the manager does with the stores `NSMigrationManager` reads through its `sourceContext` and writes through its `destinationContext`; the header says these are created lazily as two Core Data stacks, one for reading and one for writing. The destination is a separate store: if none exists at the destination URL one is created, otherwise the migration appends to it. Because objects are created before relationships, the manager keeps **association tables** linking each source object to the destination objects made from it. `associate(sourceInstance:withDestinationInstance:for:)` fills them, and `destinationInstances(forEntityMappingName:sourceInstances:)` and `sourceInstances(forEntityMappingName:destinationInstances:)` read them. A policy that meets a problem it cannot fix can throw, or call `cancelMigrationWithError(_:)` on the manager, which aborts the run and makes `migrateStore` fail with that error. ## Traps - **Driving `NSMigrationManager` yourself.** `migrateStore(from:type:options:mapping:to:type:options:)` writes a new store at a destination URL, and `usesStoreSpecificMigrationManager` defaults to `true`. Its header says a store-specific migration manager need not perform the usual callbacks, so set it to `false` when your policy must run. - **Progress.** `migrationProgress` (0 to 1) and `currentEntityMapping` are observable, but only on a manager you created; automatic migration does not hand you one. - **Which stores it covers.** Automatic migration looks for a mapping model from the store's own version to the current one, so a store from an older version than the mapping's source needs a mapping of its own. On iOS 17 and later, staged migration can do the same job with handlers instead of a mapping model, and many teams prefer it there.

  • In Core Data, why might a custom entity migration policy never run when you call NSMigrationManager yourself?
    `usesStoreSpecificMigrationManager` defaults to `true`, which lets a store-specific migration manager do the work, and the header says such a manager is not guaranteed to perform the usual callbacks. With an inferred mapping and that default, the policy can be skipped without any error. Set the property to `false` before calling `migrateStore` when the policy must run.
  • In Core Data, how would you show progress for a migration that uses a mapping model?
    Run it yourself instead of relying on automatic migration: create an `NSMigrationManager` with the source and destination models, observe `migrationProgress`, a value from 0 to 1, and `currentEntityMapping`, and call `migrateStore(from:type:options:mapping:to:type:options:)` off the main thread. When it finishes, replace the old store with the new one and load it normally.

  • Lightweight migration will create the Artist objects if the relationship has an inverse.
  • Overriding createDestinationInstances without super needs nothing more than inserting the object.
  • Typing the bare Swift class name into Custom Policy is enough for Core Data to find it.
  • A mapping model keeps matching after you change its source or destination model's schema.
  • Use the app's generated Album class on source objects during the migration.