Database Reference
In-Depth Information
The currentModel property is lazy, so you load it only once since it should return
the same thing every time. Core Data will, by default, return the “current” data
model when loading the model using the .momd folder URL, and return a properly
initialized NSManagedObjectModel .
Of course, if the model you have isn't the current model, that's the time to run the
migration! Add a starter method to the class (which you'll fill in later), as follows:
func performMigration() {
}
Now, head up to the stack property you added earlier. Change that definition to the
following:
var stack: CoreDataStack {
if !storeIsCompatibleWith(Model: currentModel) {
performMigration()
}
return CoreDataStack (modelName: modelName ,
storeName: storeName , options: options )
}
In the end, the computed property will return a CoreDataStack instance. Before it
does so, it checks if the store specified in the initialization is compatible with what
Core Data determines to be the current version of the data model. If the store can't
be loaded with the current model, then it needs to be migrated.
You now have a self-aware Core Data stack that can tell you what version it is!
Build the project to make sure everything compiles. The next step is to add the
custom migration logic.
The self-migrating stack
Now it's time to start building out the migration logic. Add the big method that does
the heavy lifting:
func migrateStoreAt(URL storeURL: NSURL ,
fromModel from: NSManagedObjectModel ,
toModel to: NSManagedObjectModel ,
mappingModel: NSMappingModel ? = nil ) {
// 1
let migrationManager = NSMigrationManager (sourceModel: from,
destinationModel:to)
// 2
Search WWH ::




Custom Search