【问题标题】:How to prevent temporaryContext run concurrently with migratePersistentStore如何防止temporaryContext与migratePersistentStore同时运行
【发布时间】:2015-09-22 19:23:26
【问题描述】:

我有一个代码部分,我调用migratePersistentStore,我想阻止任何temporaryContext 同时做任何事情,如何?

我的想法是基于semaphoredispatch_group

代码 A:

dispatch_group_wait(dgLoadMain, DISPATCH_TIME_FOREVER)
dispatch_semaphore_wait(semaLoadMain, DISPATCH_TIME_FOREVER)

mainMOC!.performBlockAndWait({

    mainMOC!.persistentStoreCoordinator!.migratePersistentStore(/* ... */)
})

dispatch_semaphore_signal(semaLoadMain)

代码 B:

dispatch_group_enter(dgLoadMain)
dispatch_semaphore_wait(semaLoadMain, DISPATCH_TIME_FOREVER)
dispatch_semaphore_signal(semaLoadMain)
let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
context.parentContext = mainMOC

var context: NSManagedObjectContext
context.performBlockAndWait({

    // .. some code I do not want to run when migrating persistent store

    context.save(nil)
})

mainMOC.performBlockAndWait({

    mainMOC.save(nil)
})

dispatch_group_leave(dgLoadMain)

你怎么看?有什么更好的解决方案吗?在这种情况下可以使用dispatch_barrier_async吗?

【问题讨论】:

    标签: ios core-data grand-central-dispatch nsmanagedobjectcontext barrier


    【解决方案1】:

    一个更好的解决方案是设计应用程序,这样就没有必要了。在迁移过程中,您实际上是在阻止整个应用程序(包括 UI 线程)执行任何操作。

    最好将其开发为状态引擎,在后台进行迁移,然后在迁移完成时通知 UI。这样,您的应用程序就可以响应系统(并且您不会被操作系统杀死),并且还可以向用户提供潜在的状态更新。

    您在这里所做的只是乞求操作系统在迁移过程中终止您的应用程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      • 2015-07-26
      • 2011-09-10
      • 1970-01-01
      • 2022-11-09
      • 1970-01-01
      • 2020-02-23
      相关资源
      最近更新 更多