如何使用dispatch_async按照UITableView中的单元格顺序下载照片? [英] How can i download photos by order of cells in UITableView with dispatch_async?
问题描述
我有一个有照片的UITableView,我从URL获取这些照片,我使用该块异步下载这些照片,我希望这些照片按照UITableView中的单元格顺序下载?
I have a UITableView that has photos, i get these photos from URLs and i use the block for downloading these photo asynchronously, and i want these photos be downloaded by order of the cells in the UITableView?
// Download the images from the review of the businesses and put them into the "imageArray"
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://feature.site.com%@",entry.avatarUrl]]];
UIImage *imageField = [[UIImage alloc] initWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
[imageArray addObject:imageField];
photo.image = imageField;
});
});
推荐答案
你需要这样做:
1)首先创建并且可变数组充满NSNull。
1) First create and mutable array full of NSNull.
2)在CellForRowAtIndexPath上,询问该indexPath处的数组.row等于NSNull。
2) On CellForRowAtIndexPath, ask if the array at that indexPath.row is equal to NSNull.
2.1)如果相等,请下载如下图像:
2.1) If is equal, download the image like this:
dispatch_queue_t bgqueue = dispatch_queue_create("com.yourApp.yyourclass.bgqueue", NULL);
dispatch_async(bgqueue, ^{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://feature.site.com%@",entry.avatarUrl]]];
UIImage *imageField = [[UIImage alloc] initWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
[imageArray addObject:imageField atIndex:indexPath.row];
tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone]
});
});
dispatch_release(bgqueue);
2.2)如果不相等(有图像),只需在图像中设置图像。
2.2) If is not equal(have an Image) just set the image in the array.
photo.image = [imageArray objectAtIndex:indexPath.row];
通过执行此操作,您的图像可以保持单元格顺序,并提高滚动的性能。
By Doing this your images keep cell order and you increase the performance of the scrolling.
PD-1:您应该使用一个库来处理图像的下载和缓存,如HTTPRequest
PD-1: You should use a library that handles the download and caching of the images like HTTPRequest
PD-2:在你的ReReceiveMemoryWarning你应该这样做:
PD-2: In your Did reReceiveMemoryWarning you should do something like this:
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
[imagesArray removeAllObjects];
//Fill the array with NSNull's again;
}
进一步改善:
在数组中你可以有3种状态:
In the Array you could have 3 states:
- NSNull:无图像
- NewState(EG。some string):正在下载图片。
- UIImage:图片已下载。
使用此功能,如果在下载图像时连续向上和向下滚动,可以防止多次下载相同的图像。
With this you could prevent for downloading several times the same image if you scroll up and down continuously while the images are being downloaded.
这篇关于如何使用dispatch_async按照UITableView中的单元格顺序下载照片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!