我正在展示一张桌子。每行都有一个从 URL 加载的图像图标。
由于同步下载图像会阻塞 UI,因此我通过大型中央调度实现了异步方式。
我的问题是,当我向下和向上滚动时,由于正在重复使用单元格,因此会显示不正确的图像。
我可以猜到为什么会发生这种情况 - 这是因为重新使用的单元格更新了图像,因此,以前的单元格现在将具有新下载的错误图像。解决这个问题的理想方法是什么?
这是我的代码。
对于下载的每个图像,我将其存储在一个名为“ImageStore”的单例类中。
// set the data for each cell - reusing the cell
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:@"UITableViewCell"];
}
// setting the image for each cell
// first check if there is UIImage in the ImageStore already
NSString *imageUrl = [obj objectForKey:@"image"];
if (imageUrl) {
if ([[ImageStore sharedStore] imageForKey:imageUrl]) {
[[[tableView cellForRowAtIndexPath:indexPath] imageView] setImage:[[ImageStore sharedStore] imageForKey:imageUrl]];
} else {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:[obj objectForKey:@"image"]]]];
dispatch_sync(dispatch_get_main_queue(), ^{
[[ImageStore sharedStore]setImage:image forKey:imageUrl];
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]withRowAnimation:UITableViewRowAnimationNone];
[[[tableView cellForRowAtIndexPath:indexPath] imageView] setImage:image];
});
});
}
}
return cell;
}