设置持久存储协调器时,请确保指定希望它在设置时传递的选项字典中自动迁移数据(如果适用)。
像这样:
do {
try self?.psc?.addPersistentStore(
ofType: NSSQLiteStoreType,
configurationName: nil,
at: url,
options: [
NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true
])
print("Core Data Store setup")
} catch {
print("Error migrating store: \(error)")
}
如果您正在为iOS 10+构建,另一个选择是使用NSPersistentContainer,它为您管理上下文、模型和持久存储协调器。
(我还没有尝试过使用nspersistentcontainer进行迁移,但我想我会让您了解它们,以防它简化了您的工作)。
下面是一个使用nsPersistentContainer的核心数据堆栈示例,而不是使用带有持久存储协调器的旧样式,等等:
import CoreData
class CoreDataStack {
// added in case you want to initialize the persistent container with a specific managed
// object model via
// let container = NSPersistentContainer.init(name: DataModel, managedObjectModel: managedObjectModel())
internal func managedObjectModel() -> NSManagedObjectModel {
let bundle = Bundle(for: AppDelegate.self)
guard let url = bundle.url(forResource: "DataModel", withExtension: "momd") else {
fatalError("Error loading model from bundle")
}
guard let mom = NSManagedObjectModel(contentsOf: url) else {
fatalError("Error initializing mom from: \(url)")
}
return mom
}
internal lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "DataModel")
container.loadPersistentStores(completionHandler: { [weak self](storeDescription, error) in
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
if let error = error {
print("CoreData: error \(error), \(String(describing: error._userInfo))")
}
})
return container
}()
func performUITask(_ block: @escaping (NSManagedObjectContext) -> Void) {
persistentContainer.viewContext.perform {
block(self.persistentContainer.viewContext)
}
}
func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) {
persistentContainer.performBackgroundTask(block)
}
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("CoreData: Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}