dispatch_async in NSManagedObjectContext's performBlock

女生的网名这么多〃 提交于 2019-12-07 11:54:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!