问题
I have a code part where I call migratePersistentStore
and I want to prevent any temporaryContext
to do anything in the same time, how?
My idea is based on a 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 it? Any bette solution? Is it possible to use dispatch_barrier_async
in this case?
回答1:
A far better solution is to design the application so that this is not necessary. You are effectively blocking the entire application (including the UI thread) from doing anything while a migration is happening.
Better to develop this as a state engine, do the migration in the background and then notify the UI when the migration is complete. That way your application is responsive to the system (and you won't get killed by the OS) and can also provide potential status updates to the user.
What you are doing here is just begging for the OS to kill your app mid migration.
来源:https://stackoverflow.com/questions/31232431/how-to-prevent-temporarycontext-run-concurrently-with-migratepersistentstore