iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🍎

Lightweight Migration in CoreData

に公開

If you update an app that already has columns added while it is installed, the app will crash upon launch.

You need to migrate CoreData to prevent the app from crashing.

Lightweight migration is a feature that automatically detects the addition or removal of attributes and migrates CoreData for you.

How to do it

For more details, please refer to the link below.

Migrating your data model automatically | Apple Developer Documentation

Add Swift code

Add the following code.

container.persistentStoreDescriptions.forEach { description in
    // Enable automatic migration
    description.setOption(true as NSNumber, forKey: NSMigratePersistentStoresAutomaticallyOption)
    // Enable automatic mapping model inference
    description.setOption(true as NSNumber, forKey: NSInferMappingModelAutomaticallyOption)
}

Work in Xcode

  1. With the xcdatamodeld file selected, go to Editor, then Add Model Version...
  2. Create a new model version, something like AppName 2
  3. Select AppName 2, and in the inspector area, change the Current setting under Model Version to the newly created model version
  4. Add columns and models in AppName 2

References

Migrating your data model automatically | Apple Developer Documentation

I have summarized the knowledge I gained from developing at home every day for two and a half years! Please take a look if you'd like.

https://doityourself.jp/articles/2026/full-platform-development/

Discussion