12

I'm learning about blocks from a Stanford video. I'm now at the part which explains core data. The teachers mentions something about:

- (void)openWithCompletionHandler:(void (^)(BOOL success))completionHandler;

He said that completionhandler block will be called in the thread which called the method. So basically the method runs async but the blocks get called on the thread, lets assume main.

So my question is do all blocks run on the thread from where the method call was made. To illustrate why I ask this question, I have a Async class which does request to a server.

The format of all these methods is like this:

- (void) getSomething:(id <delegateWhatever> const)delegate{
   goto background thread using GCD..
   Got result from server...
   Go back to main thread and call the delegate method...
}

When I use blocks I do not need to worry about going back to main thread if they will be called where the call was made?

Hope this is clear,

Thanks in advance

4

2 回答 2

15

如果某些东西异步运行,您应该阅读文档以了解将在哪个线程上执行,例如完成块将被执行。如果是你的代码,你在这里负责,你可以使用全局 GCD 队列,你可以创建自己的队列并在那里执行它或其他什么......

通常,块的行为类似于函数或方法调用,它在调用它的线程上执行。甚至有可能同时从 2 个不同的线程执行同一个块。

并且要明确一点:即使您正在使用块,您也需要关心回到主线程,当然如果有必要的话

于 2013-11-05T13:31:29.040 回答
4

没有什么会强制在特定线程上调用块,因此取决于特定方法是否需要担心它的回调在主线程上。(实际上,我不记得曾经见过一个库,其中在主线程上调用的方法不会在主线程上调用其完成处理程序。但是您仍然需要阅读您正在使用的特定库和方法的文档,一如既往

于 2013-11-05T13:08:29.077 回答