core-datacore-data-migration

Core Data migrations requirements


I have a couple of questions about Core Data migrations that I can't seem to find answers for.

  1. I am making a small change in my Core Data model file ... specifically changing the 'transformers' in some of the Transformable attributes, from blank to NSSecureUnarchiveFromData (to get rid of warnings about NSKeyedUnarchiveFromDataTransformerName). Do I need to create a new model and do lightweight migration for this? Or does this not affect anything in the model?
  2. With Xcode12.2, if I make a change to my model (like adding an attribute or a new entity), and I don't create a new model version, and just run the app ... it doesn't crash! It used to always throw the "Can't find model for source store" error. Did something change around this in recently? Or am I doing something wrong?

Thanks.


Solution

  • Core Data decides whether model migration is needed by comparing version hashes. The data model has one, and when you create a persistent store, that version hash is saved in the store file. Any time they're different, migration is needed. After migration, the store file's hash is updated to match the new model.

    The only things that matter for version hashes are things that affect how the SQLite database is set up. If changing something would mean the SQLite schema changes, then the version hash changes. This does not include the transformer name. If you're interested in a detailed explanation, look up the versionHash property on NSEntityDescription, NSPropertyDescription, NSAttributeDescription, and NSRelationshipDescription

    You can also add your own version hash modifier string to force the version hash to change, if you ever want to force a migration for some reason.

    For simple migrations, Core Data is more forgiving than it used to be. Lightweight migration with automatic mapping model generation is active by default (shouldMigrateStoreAutomatically and shouldInferMappingModelAutomatically are both true by default). Unless you specifically turn it off, lightweight migration just happens when needed. It's still a good idea to keep different model versions, if only to keep track of how the project changes over time, but if you don't it'll often work anyway.