[英]How can i download photos by order of cells in UITableView with dispatch_async?
我有一個包含照片的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 reReceiveMemoryWarning中,您應該執行以下操作:
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
[imagesArray removeAllObjects];
//Fill the array with NSNull's again;
}
進一步改進:
在數組中,您可以有3種狀態:
這樣,如果在下載圖像時連續上下滾動,則可以防止多次下載同一圖像。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.