CoreData 数据迁移的问题
2020-06-19 本文已影响0人
Ian_
- 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)
}
}
```