我有一个UITableView有照片,我从url获取这些照片我使用块异步下载这些照片,我希望这些照片下载的顺序单元格在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的可变数组
2)在CellForRowAtIndexPath上,询问该indexPath上的数组。row = NSNull
2.1)如果相等,则像这样下载图像:
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)如果不等于(有一个图像),就在数组中设置图像。
photo.image = [imageArray objectAtIndex:indexPath.row];
通过这样做,您的图像保持单元格的顺序,并提高滚动的性能。
PD-1:您应该使用一个库来处理图像的下载和缓存,如HTTPRequest
PD-2:在你的Did recreceivememywarning中,你应该这样做:
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
[imagesArray removeAllObjects];
//Fill the array with NSNull's again;
}
进一步改进:
在数组中你可以有三种状态:
- NSNull: No Image
- NewState(如。
- UIImage: Image download .
如果你在下载图片的时候连续上下滚动,你可以防止下载几次相同的图片