在核心数据迁移上保留现有数据

时间:2019-01-05 09:51:38

标签: ios swift core-data core-data-migration

我正在通过以下步骤进行核心数据的轻量级迁移:

  1. 版本化数据模型

  2. 创建新的与新数据模型兼容的persistenceStore。

    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator =   {
            // Initialize Persistent Store Coordinator
            let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    
            // URL Persistent Store
        let URLPersistentStore = self.applicationStoresDirectory().appendingPathComponent("FieldSense.sqlite")
    
            do {
                // Declare Options
                let options = [ NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true ]
    
                // Add Persistent Store to Persistent Store Coordinator
                try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: URLPersistentStore, options: options)
    
            } catch {
                let fm = FileManager.default
                var isDir : ObjCBool = false
                if  fm.fileExists(atPath: (URLPersistentStore?.path)!, isDirectory: &isDir){
              //  if fm.fileExistsAtPath(URLPersistentStore.path!) {
                    let nameIncompatibleStore = self.nameForIncompatibleStore()
                    let URLCorruptPersistentStore = self.applicationIncompatibleStoresDirectory().appendingPathComponent(nameIncompatibleStore)
    
                    do {
                        // Move Incompatible Store
                    //    try fm.moveItemAtURL(URLPersistentStore, toURL: URLCorruptPersistentStore)
                        try fm.moveItem(at: URLPersistentStore!, to: URLCorruptPersistentStore!)
    
                    } catch {
                        let moveError = error as NSError
                        print("\(moveError), \(moveError.userInfo)")
                    }
                }
    
                do {
                    // Declare Options
                    let options = [ NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true ]
    
                    try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: URLPersistentStore, options: options)
    
                } catch {
                    let storeError = error as NSError
                    print("\(storeError), \(storeError.userInfo)")
                }
    
                // Update User Defaults
                let userDefaults = UserDefaults.standard
                userDefaults.set(true, forKey: "didDetectIncompatibleStore")
            }
    
            return persistentStoreCoordinator
    }()
    

但是,当用户从应用商店更新应用时,现有的用户数据将被删除。可能是什么原因?

0 个答案:

没有答案