How to prevent concurrent running whileContext with migratePersistentStore
I have a piece of code in which I am calling migratePersistentStore
and I want some element to temporaryContext
do something at the same time, how?
My idea is based on semaphore
and a dispatch_group
.
code A:
dispatch_group_wait(dgLoadMain, DISPATCH_TIME_FOREVER)
dispatch_semaphore_wait(semaLoadMain, DISPATCH_TIME_FOREVER)
mainMOC!.performBlockAndWait({
mainMOC!.persistentStoreCoordinator!.migratePersistentStore(/* ... */)
})
dispatch_semaphore_signal(semaLoadMain)
code 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)
What do you think about this? Any bette solution? Can I use it dispatch_barrier_async
in this case?
source to share
The best solution is to design the application so that it is not necessary. You are effectively blocking the entire application (including the UI thread) from doing anything during the migration.
Better to design this as a state mechanism, perform the migration in the background, and then notify the UI when the migration is complete. This way your application is responsive to the system (and you won't be killed by the operating system) and can also provide the user with potential status updates.
What you are doing here is just asking the OS to kill the average application migration.
source to share