使用类别异步下载图像和更新TableView单元格,而不使用任何库



我们有SDWebImage库,它为图像下载和缓存提供了一个类别(UIImageView+SDWebcache.m),它还在UITableView或UIColollectionView单元格上正确设置每个类别。我不想使用任何库,也不想创建类似的类别。下载图像后,我如何跟踪此图像所属的单元格,并查看该单元格是否可见,以避免将图像设置在重用该单元格的另一个indexPath上。我写的代码(这里删除了缓存逻辑):

// Inside the category, I have this method
-(void)SetThumbImageFordownloadURL:(NSString*)url {
[MyDownloadManager asyncImageDownload:url withProgressHandler:nil andCompletionHandler:^(UIImage *image, NSUInteger errorCode){
dispatch_async(dispatch_get_main_queue(), ^{
//if cell is not visible and is reused by another index, this image wil be set on wrong cell
[self setImage:image];
});
}];
}

选项1:在单元格中保留对URL的引用作为属性,并在重用方法中消除它。

在您的代码块中,返回图像的实际URL,并执行以下操作:

[MyDownloadManager asyncImageDownload:url withProgressHandler:nil andCompletionHandler:^(UIImage *image, NSURL *url, NSUInteger errorCode){
dispatch_async(dispatch_get_main_queue(), ^{
//check if current hold key is equal to url and only then set the image.

[self setImage:image];
});
}];

选项2/微调:在您的"MyDownloadManager"中添加一个取消方法,并在您的tableview/collectionview的"didEndDisplay"方法中取消当前下载。

相关内容

最新更新