美文网首页
CoreData 数据迁移的问题

CoreData 数据迁移的问题

作者: Ian_ | 来源:发表于2020-06-19 18:12 被阅读0次
  1. coordinator 不能重复添加 PersistentStore, 在使用 NSPersistentContainer的时候需要注意, 默认会创建一个在 Library/Application Support 文件夹下的数据库, 也可以使用NSPersistentStoreDescription来指定存储位置, 如果在迁移之前直接使用 newStoreUrl, 那么在迁移的时候, 就不能判断newStoreUrl 是否存在, 因为 container.loadPersistentStores, 的时候已经创建了新的数据库文件, 所以肯定存在. 所以为了避免这个问题, 可以不判断路径, 或者可以在 container.loadPersistentStores 之前进行数据迁移, 并且, NSPersistentStoreCoordinator使用新建立的.
let container = NSPersistentContainer(name: modelName)
let description = NSPersistentStoreDescription(url: newStoreUrl)
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
container.persistentStoreDescriptions = [description]

container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        })
func migratePersistentStore(oldStoreUrl: URL) {
         let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        var storeOptions = [AnyHashable : Any]()
        storeOptions[NSMigratePersistentStoresAutomaticallyOption] = true
        storeOptions[NSInferMappingModelAutomaticallyOption] = true

        var targetUrl : URL? = nil
        var needMigrate = false
        
        if FileManager.default.fileExists(atPath: oldStoreUrl.path) {
            needMigrate = true
            targetUrl = oldStoreUrl
        }
        
        if targetUrl == nil {
            return
        }
        
        if needMigrate {
            do {
                try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: targetUrl!, options: storeOptions)
                if let store = coordinator.persistentStore(for: targetUrl!) {
                    do {
                        try coordinator.migratePersistentStore(store, to: newStoreUrl, options: storeOptions, withType: NSSQLiteStoreType)
                    } catch {
                        print(error.localizedDescription)
                        return
                    }
                }
            } catch {
                print(error.localizedDescription)
                return
            }
            deleteDocumentAtUrl(url: oldStoreUrl)
        }
    }
    ```

相关文章

网友评论

      本文标题:CoreData 数据迁移的问题

      本文链接:https://www.haomeiwen.com/subject/shdbxktx.html