CoreData 数据迁移的问题

2020-06-19  本文已影响0人  Ian_
  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)
        }
    }
    ```
上一篇 下一篇

猜你喜欢

热点阅读