问题
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:
You need to do something like this:
1) First create and mutable array full of NSNull.
2) On CellForRowAtIndexPath, ask if the array at that indexPath.row is equal to NSNull.
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) 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: You should use a library that handles the download and caching of the images like HTTPRequest
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;
}
Further Improvement:
In the Array you could have 3 states:
- NSNull: No Image
- NewState(EG. some string): Image being downloaded.
- UIImage: Image Downloaded.
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.
来源:https://stackoverflow.com/questions/8636499/how-can-i-download-photos-by-order-of-cells-in-uitableview-with-dispatch-async