Hi everyone,
I’m working on an offline-first iOS app using Core Data.
I have a question about safe future updates: in my project, I want to be able to add new optional fields to existing Entities or even completely new Entities in future versions — but nothing else (no renaming, deleting, or type changes).
Here’s how my current PersistenceController looks:
import CoreData
struct PersistenceController {
static let shared = PersistenceController()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "MyApp")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
print("Core Data failed to load store: \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
}
}
Do I need to explicitly set these properties to ensure lightweight migration works?
shouldMigrateStoreAutomatically = true shouldInferMappingModelAutomatically = true
Or, according to the documentation, are they already true by default, so I can safely add optional fields and new Entities in future versions without breaking users’ existing data?
Thanks in advance for your guidance!
Adding new fields, optional or not, and adding new entities, are lightweight migrat-able. shouldMigrateStoreAutomatically and shouldInferMappingModelAutomatically are by default true, and so if detecting the model change, Core Data will automatically trigger a lightweight migration, without the need of explicitly setting the two properties to true. So you are good to go.
Best,
——
Ziqiao Chen
Worldwide Developer Relations.