Why data is removed if I enable light-weight migration in swift 5?

315 views Asked by At

I have successfully launched 1st version of my App with MyProject.xcdatamodel. Now my 2nd version is under development and I created new model version named MyProject2.xcdatamodel based on MyProject.xcdatamodel and set it to Current. I have enabled light-weight migration as following in my AppDelegate:

lazy var persistentContainer: NSPersistentContainer = {

let container = NSPersistentContainer(name: "MyProject")

    // Support for light-weight migration 
    /*-------------------------------------------------------*/
    let description = NSPersistentStoreDescription()
    description.shouldMigrateStoreAutomatically = true
    description.shouldInferMappingModelAutomatically = true
    container.persistentStoreDescriptions = [description]
    /*-------------------------------------------------------*/

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

After doing this, I first installed my old version, and then installed new version on top of old. While launching new version, there is no data found from one of my database table of old model which I did not have touch. If I remove those 4 lines of migration, it is getting data.

What may be the reason? Is there anything wrong I am doing for light-weight migration?

1

There are 1 answers

0
mhammad alkhalaf On

You need to specify the URL for the location of the actual model's database location.

    lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: Constants.yourModelName)

    if let storeURL = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appendingPathComponent("\(Constants.yourModelName).sqlite") {
        /*add necessary support for migration*/
        let description = NSPersistentStoreDescription(url: storeURL)
        description.type = NSSQLiteStoreType
        description.shouldMigrateStoreAutomatically = true
        description.shouldInferMappingModelAutomatically = true
        container.persistentStoreDescriptions =  [description]
    }

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error {
            print("Unresolved error, \((error as NSError).userInfo)")
        }
    })
    return container
}()