我只是想确认为什么需要这个。
我将此代码添加到KIImagePager ( cocoapod)中,以加载应用程序本地的图像(默认代码从url加载图像)。
以下是我的工作代码,基于一位同事的建议:
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,它可以工作,但不是我想要的方式(当我开始滚动时,图像分页滚动视图上的一些图像还没有加载)。但它们最终还是会加载。
我的问题是,主队列上的sync调用是否会将图像返回到UI (在主队列上)?因为它确实可以在删除第二个异步的情况下工作。
发布于 2013-06-09 03:20:09
内部调度在主线程上执行其代码块。这是必需的,因为所有UI操作都必须在主线程上执行。并且您的图像下载代码(执行此代码片段的上下文)可能在后台线程上。
外部调度在后台线程上执行其块。它给出的块是在主线程上执行的块。因此,可以安全地移除外部块。
这是你正在使用的成语的提纲。
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
});
});发布于 2013-06-09 03:16:15
您应该只使用主线程上的UI对象。如果你不这样做,你会遇到一些问题。正如您所看到的,第一个问题是UI对象的更新将会延迟。第二个问题是,如果您尝试从多个线程同时更改UI对象,应用程序可能会崩溃。您应该只使用主线程上的UI对象。
https://stackoverflow.com/questions/17002912
复制相似问题