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
- With the xcdatamodeld file selected, go to
Editor, thenAdd Model Version... - Create a new model version, something like
AppName 2 - Select
AppName 2, and in the inspector area, change theCurrentsetting underModel Versionto the newly created model version - 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.
Discussion