How to check whether a Core Data store needs migration

When using Core Data I typically rely on automatic lightweight migration to upgrade the persistent store to the latest model version. Today I needed to determine whether the store was migrated.

Creating my persistent store by calling addPersistentStoreWithType:configuration:URL:options:error: with the options to automatically kick off lightweight migration succeeds as long as a migration is possible, but doesn’t indicate when a migration has occurred.

I could just call addPersistentStoreWithType:configuration:URL:options:error: without the migration options, and if that throws an error, then I know I need to migrate. But it turns out there’s a more efficient way to check: simply call isConfiguration:compatibleWithStoreMetadata: on the object model before attempting to open the store.

code snippet:

let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(ofType: NSSQLiteStoreType, at: storeURL, options: nil)

if !objectModel.isConfiguration(withName: nil, compatibleWithStoreMetadata: metadata) {
    needsMigration = true
}

Reading: Initiating the Migration Process