【发布时间】:2014-02-24 19:36:08
【问题描述】:
谁能告诉我我的代码有什么问题。它似乎有效,但是当我快速滚动然后停止时,UIImageView 在显示正确的图片之前循环浏览几张图片。这发生得很快但很明显。
if (![post objectForKey:@"photoData"] && ![post objectForKey:@"isDownloadingPhoto"]){
cell.instagramPhoto.image = nil;
[[combinedArray objectAtIndex:indexPath.row] setObject:@"loading" forKey:@"photoData"];
[[combinedArray objectAtIndex:indexPath.row] setObject:@"yes" forKey:@"isDownloadingPhoto"];
[cell.instagramPhoto setAlpha:0];
if (instagramURL != nil){
dispatch_async(kBgQueue, ^{
int index = indexPath.row;
NSData* data = [NSData dataWithContentsOfURL: instagramURL];
if (data.length > 0){
[[combinedArray objectAtIndex:index] setObject:data forKey:@"photoData"];
[[combinedArray objectAtIndex:index] setObject:@"no" forKey:@"isDownloadingPhoto"];
UIImage *image = [UIImage imageWithData:data];
dispatch_sync(dispatch_get_main_queue(), ^{
cell.instagramPhoto.image = image;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.4f];
cell.instagramPhoto.alpha = 1.0;
[UIView commitAnimations];
});
}
});
}
}
else if ([[post valueForKey:@"isDownloadingPhoto"] isEqualToString:@"yes"]) {
NSLog(@"loading");
cell.instagramPhoto.image = nil;
}
else {
NSData *data = [post valueForKey:@"photoData"];
NSLog(@"saved");
UIImage *image = [UIImage imageWithData:data];
cell.instagramPhoto.image = image;
}
【问题讨论】:
-
所有这些都在
cellForIndexPath? -
是的,都在 cellForRowIndexPath 内
-
而且你在 presumable 中也有一些单元重用逻辑。我怀疑这是正在发生的事情 -
cellForIndex...被调用一个单元格,你开始异步下载过程,滚动表格视图,这个单元格在另一个cellForIndex中被重用 -
有什么办法可以避免这种情况吗?如果不是,在 tableviewCell 中缓存图像的推荐方法是什么?
-
让我把它包装成一个答案
标签: ios objective-c uitableview caching asynchronous