dispatch_async中的dispatch_sync

我只是想确认为什么这是必要的。

我将这段代码添加到KIImagePager(一个cocoapod)来加载应用程序本地的图像(默认代码从一个url加载图像)。

这是我的工作代码基于什么同事build议:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ dispatch_sync(dispatch_get_main_queue(), ^{ [imageView setImage:[UIImage imageNamed:[aImageUrls objectAtIndex:i]]];; }); }); 

我注意到,如果我拿出内部dispatch_sync,它的工作原理,但不是我想要的方式(当我开始滚动时图像分页器滚动视图上的一些图像尚未加载)。 但他们最终加载。

我的问题是,主队列上的同步调用是否将图像返回到UI(主队列上)? 因为它确实与删除的第二个asynchronous一起工作。

内部调度在主线程上执行其代码块。 这是必需的,因为所有UI操作必须在主线程上执行。 而你是图像下载代码(执行此代码段的上下文)可能在后台线程上。

外部调度在后台线程上执行其块。 它给出的块是在主线程上执行的块。 因此,外部块可以安全地移除。

Hrs你正在使用的成语大纲。

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ // do blocking work here outside the main thread. // ... // call back with result to update UI on main thread // // what is dispatch_sync? Sync will cause the calling thread to wait // until the bloc is executed. It is not usually needed unless the background // background thread wants to wait for a side effect from the main thread block dispatch_sync(dispatch_get_main_queue(), ^{ // always update UI on main thread }); }); 

您应该只使用主线程上的UI对象。 如果你不这样做,你会遇到一些问题。 首先,正如你所看到的那样,UI对象将在更新中延迟。 其次,如果您尝试从多个线程同时更改UI对象,应用程序可能会崩溃。 您应该只使用主线程上的UI对象。