问题
According to the WWDC 2012 video, "Core Data Best Practices", dispatch_sync
should be used to run some kind of callback in performBlock
of context, which is created as a type of NSPrivateQueueConcurrencyType
.
Why is that?
Can I use dispatch_async(dispatch_get_main_queue(), 0)
... to call some UI-related callbacks in private queue's context's performBlock
?
回答1:
No. NSPrivateQueueConcurrencyType
manages it's own internal queue, and does not enjoy you trying to leave one of it's threads to do what you want to do (in fact, I believe it throws exceptions when this type of behavior occurs). There's a few ways of handling this, of course signalling semaphores being the more acceptable design pattern to get the truly "async feel", but as you note, dispatch_sync
is usually the way to go.
回答2:
Google got me here, so if anyone is new to this stuff as I am, and would benefit from a code example, here is one:
__block dispatch_queue_t currentQ = dispatch_get_current_queue();
[managedObjectContext performBlock:^{
//do the stuff you need to do in a background thread
dispatch_sync(currentQ, ^(){
//callback code for once the background stuff is complete
});
}];
来源:https://stackoverflow.com/questions/13468705/dispatch-async-in-nsmanagedobjectcontexts-performblock