使用块从后台线程加载图像 [英] loading images from a background thread using blocks
问题描述
我有以下方法,它基本上调用请求在后台线程中加载图像的NSData数组:
I have the following method, which basically calls a request to load an array of NSData of images in the background thread:
[query findObjectsInBackgroundWithBlock:^(NSArray * objects, NSError * error){
}];
在这种情况下,objects是NSData的数组。问题是如果我要加载100个图像(数组中有100个元素)。这意味着用户必须等待一段时间才能看到UITableView中出现的任何图像。我想要做的是让他们看到一个图像一旦可用/加载..我是否必须更改代码,以便它执行100个后台线程来加载图像?
In this case objects is an array of the NSData. The issue is that if I have 100 images to load (100 elements in the array). This means that the user will have to wait for quite some time to see any image showing up in a UITableView. What I want to do is for them to see an image once it is available/loaded.. do I have to then change the code so that it does 100 background threads to load the image?
推荐答案
你可以在你的cellForRowAtIndexPath中实现类似的东西:
you could implement something like this in your cellForRowAtIndexPath:
这样你就可以在后台加载每个图像了只要其装载相应的单元格更新在mainThread。
That way you load each image in the background and as soon as its loaded the corresponding cell is updated on the mainThread.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
NSData *data0 = [NSData dataWithContentsOfURL:someURL];
UIImage *image = [UIImage imageWithData:data0];
dispatch_sync(dispatch_get_main_queue(), ^(void) {
UIImageView* imageView = (UIImageView*)[cell viewWithTag:100];
imageView.image = image;
});
});
这篇关于使用块从后台线程加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!