【发布时间】:2015-01-11 19:21:29
【问题描述】:
我在表格视图中异步加载图像。在慢速连接时,单元格中的图像会不断闪烁/变化(我假设它来自重复使用单元格)。我遵循了其他一些相关问题的建议,包括:
- 缓存图像
- 设置占位符图片
在正常连接下工作正常,但在 EDGE 和慢速网络上,问题仍然存在。我想知道是否是网络请求备份的全局队列?如果是这样,我该如何解决?
这是我的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// get the data for this photo post
NSDictionary *data = [self.streamPhotosData objectAtIndex:indexPath.row];
static NSString *CellIdentifier = @"StreamPhotoTableViewCell";
__block StreamPhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StreamPhotoTableViewCell"];
if (cell == nil) {
cell = [[StreamPhotoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.delegate = self;
// check if image in cache, else cache it
if ([[[GlobalCaches getCurrentInstance] photoCache] objectForKey:[data objectForKey:@"photoGuid"]] != nil) {
// cache hit
cell.photoImageView.image = [[[GlobalCaches getCurrentInstance] photoCache] objectForKey:[data objectForKey:@"photoGuid"]];
} else {
// set a placeholder image
cell.photoImageView.image = [UIImage imageNamed:@"placeholder.png"];
// download the image asynchronously
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
UIImage *downloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[data objectForKey:@"url"]]]];
if (downloadedImage) {
dispatch_async(dispatch_get_main_queue(), ^{
cell.photoImageView.image = downloadedImage;
// update cache
[[[GlobalCaches getCurrentInstance] photoCache] setObject:downloadedImage forKey:[data objectForKey:@"photoGuid"]];
});
}
});
}
return cell;
}
【问题讨论】:
-
当您调度回主队列时,不要使用现有的
cell引用,因为它可能已被滚动出屏幕并被重复使用。使用indexPath使用 UITableViewcellforRowAtIndexPath:方法查找正确的单元格。
标签: ios objective-c cocoa-touch