简体   繁体   中英

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

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?

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
}()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM