[英]dequeueReusableCellWithIdentifier causing problem on UIImageView
我正在加载一个500行的tableView。 问题是每一行都有不同的图片。 或者,当我使用dequeueReusableCellWithIdentifier时,这些图片将再次加载,而我正在寻找的真实图片将不会显示(我只有大约8张不同的图片:屏幕上已加载了前8张)。 如果我不使用dequeureReusableCellIdentifier,则会加载所有图片。 但这会减慢显示速度吗?
这是代码(我目前正在缓存图片):
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CustomCellIdentifier = @"CustomCellIdentifier";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier: CustomCellIdentifier];
NSLog(@"Launching CellForRowAtIndexPath");
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell"
owner:self options:nil];
if ([nib count] > 0) {
cell = self.profilCell;
} else {
NSLog(@"failed to load CustomCell nib file!");
}
}
NSUInteger row = [indexPath row];
NSDictionary *rowData = [listProfils objectAtIndex:row];
UILabel *nameLabel = (UILabel *)[cell viewWithTag:nameValueTag];
nameLabel.text = [rowData objectForKey:@"name"];
NSString *finalId = [NSString stringWithFormat:@"http://graph.facebook.com/%@/picture", [rowData objectForKey:@"id"]];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:finalId]]];
[profilPic setImage:image];
return cell;
}
谢谢 ! :)
看起来您有一个ivar profilPic
,它可能是在加载新的单元笔尖时链接的插座。 如果是这种情况,它将始终指向您加载的最后一个单元,并且不会更改刚刚出队的单元中的图像。 与其使用插座,不如使用标记来标识自定义视图。 因此,例如,如果在Interface Builder中将配置文件pic UIImageView
的标记设置为100,则可以执行以下操作:
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:finalId]]];
UIImageView* cellImageView = (UIImageView*)[cell viewWithTag:100];
[cellImageView setImage:image];
另外,我只想指出-dataWithContentsOfURL:
将在主线程上同步加载URL。 如果您正在模拟器中以快速连接进行测试,则效果会很好。 但是,如果您星期五星期五在SoHo上使用3G,则您的应用可能会被看门狗杀死。
我只是遇到了这个问题,我的解决方案是保存一个私有的NSMutableDictionary
来存储以前从Web异步加载的新图像,使用我的标识符作为键,将UIImageView
用作Object(因为我需要先加载图标图像),而当Web图像是准备好,对其进行更改,当tableView
出队返回为null时,我可以从自己的缓存中读取原始的UIImage
。
这样的事情。
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
UIImageView *imageView = [thumbnailCache objectForKey:identifier];
if (!imageView) {
cell.imageView.image = [UIImage imageNamed:@"icon.png"];
[thumbnailCache setObject:cell.imageView forKey:identifier];
} else {
cell.imageView.image = imageView.image;
}
}
当我从Web加载实际图像时,请刷新缩略图缓存。
asynchronously_load_image_from_web(^(UIImage *image) {
cell.imageView.image = image;
[thumbnailCache setObject:cell.imageView forKey:identifier];
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.