In which thread are iOS completion handler blocks called?

旧时模样 提交于 2019-12-05 21:00:17

问题


For example, in GKScore's reportScoreWithCompletionHandler (documentation), suppose you call

[score reportScoreWithCompletionHandler:^(NSError *error) {
   // do some stuff that may be thread-unsafe
}];

In which thread will the completion handler be called: the main thread, the same thread as reportScoreWithCompletionHandler was called, or a different thread (presumably the thread that the actual score reporting is done)?

In other words, does the work done in the completion handler need to be thread-safe (as in, it doesn't matter what thread it's done in)?


回答1:


In practical terms it doesn't matter.

If you need your completion to run in the main thread, just dispatch it to the main thread:

[score reportScoreWithCompletionHandler:^(NSError *error) {
    dispatch_async(dispatch_get_main_queue(), ^{
        // do your stuff here
    });
}];



回答2:


There is no specific thread for completion handlers, apple documentation says it will be a secondary thread (Definitely not the main thread). You can use DispatchQueue to access different threads in iOS.



来源:https://stackoverflow.com/questions/5267411/in-which-thread-are-ios-completion-handler-blocks-called

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