异步迁移和打开 - CoreData

时间:2017-10-12 10:41:37

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

我正在使用CoreData和FetchedResultsController。这非常有效,但是,有时我会在初始化fetchedResultsController时遇到managedObjectContext为nil。这种情况在迁移期间更常发生,因此我开始相信在迁移完成之前访问Core Data(?)。

如果是这种情况,最好在尝试访问数据之前知道迁移何时完成。

我的问题是,有没有办法异步迁移数据?

我使用此代码在AppDelegate中设置核心数据堆栈(managedObjectContext传递给didFinishLaunchingWithOptions中的初始视图控制器):

lazy var containerURL: URL = {

    return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.company.app")!

}()

lazy var managedObjectModel: NSManagedObjectModel = {

    let modelURL = Bundle.main.url(forResource: "databaseModel", withExtension: "momd")!

    return NSManagedObjectModel(contentsOf: modelURL)!
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {

    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)

    var databaseStoreURL = self.containerURL.appendingPathComponent("Data.sqlite")

    let options = [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true]

    do {

        try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: "DataBaseStore", at: databaseStoreURL, options: options)

    } catch {

        coordinator = nil

        //Handle error

    }

    return coordinator

}()

lazy var managedObjectContext: NSManagedObjectContext? = {
    let coordinator = self.persistentStoreCoordinator
    if coordinator == nil {
        return nil
    }
    var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()

0 个答案:

没有答案