0

我有一个我打电话的代码部分,migratePersistentStore我想阻止任何temporaryContext人同时做任何事情,怎么做?

我的想法是基于 asemaphore和 a dispatch_group

代码一:

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在这种情况下可以使用吗?

4

1 回答 1

2

一个更好的解决方案是设计应用程序,这样就没有必要了。当迁移发生时,您实际上阻止了整个应用程序(包括 UI 线程)做任何事情。

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

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

于 2015-07-06T21:49:32.897 回答