Sidney Liu
Sidney Liu

Reputation: 487

Swift 4 in Xcode 9 - How to lightweight Core Data migration?

My Core Data will update one more attribute and , to avoid crashing , I added a new model version as first, and furthermore: 👇👇👇

The most of the keys about this issue is that change :

coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)

options: nil in the code to

options:[NSMigratePersistentStoresAutomaticallyOption:true, NSInferMappingModelAutomaticallyOption: true]

But In my appdelegate.swift , I can’t find any “persistentStoreCoordinator”, so can I migrate CoreData in my version?

Upvotes: 1

Views: 1898

Answers (2)

user688837
user688837

Reputation: 71

The solution from Gulshan Kumar is good. In my case, it didn't work because the container already had one description object, and setting

container.persistentStoreDescriptions = [description]

effectively deleted that object, with the result that the model did not load. I used

container.persistentStoreDescriptions.append(description)

Upvotes: 5

Gulshan Kumar
Gulshan Kumar

Reputation: 411

You can achieve like this:

let container = NSPersistentContainer(name: "YourDbModelName")
let description = NSPersistentStoreDescription() 
description.shouldMigrateStoreAutomatically = true 
description.shouldInferMappingModelAutomatically = true 
container.persistentStoreDescriptions = [description]

Upvotes: 7

Related Questions