How do I migrate Core Data models?

When working with Core Data in Swift, migrating your Core Data models can be a crucial step as your application's requirements evolve. Migration allows your app to adapt to changes in the model without losing existing data, ensuring backwards compatibility.

There are two main types of migration in Core Data: lightweight migration and custom migration. Lightweight migration is suitable for simple model changes, while custom migration is necessary for more complex changes that require finer control.

Here’s a basic example of how to set up a lightweight migration in Swift:

// Set up the persistent store coordinator with the options let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) do { try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options) } catch { // Handle the error fatalError("Unresolved error \(error)") }

core data migration swift core data lightweight migration custom migration persistent store coordinator