在tableview中异步设置图像 [英] Asynchronously set images in tableview
问题描述
我使用自定义单元格 TableView
。我最初设置从 cellForRowAtIndexPath
方法中的URL抓取图像
I have a TableView
using custom cells. I initially was setting grabbing an image from a URL in the cellForRowAtIndexPath
method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSDictionary *dictObject = [places objectAtIndex:indexPath.row];
cell.nameLabel.text = [dictObject valueForKey:@"PlaceTitle"];
NSURL *url = [NSURL URLWithString:@"http://images1.fanpop.com/images/image_uploads/Mario-Kart-Wii-Items-mario-kart-1116309_600_600.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
cell.thumbnailImageView.image = image;
return cell;
}
但这使我的TableView滚动滞后。一旦我删除了图像提取,它滚动得很好,所以我知道这是我的问题。
but this was making my TableView scroll laggy. Once I removed the image fetch, it scrolled fine, so I know this is my problem.
我的问题是:如何异步获取此图像并将其设置在我的图像中细胞?是否有捷径可寻?谢谢!
My question is: how can I asynchronously fetch this image and set it in my cell? Is there an easy way to do this? Thanks!
推荐答案
步骤1:拥有包含图像的缓存。要么只是在内存中,要么在磁盘上更好。
Step 1: Have a cache containing images. Either just in memory, better on disk.
步骤2:当您需要图像时,调用一个方法,该方法从缓存中返回图像,或返回默认图像并开始下载。
Step 2: When you need an image, call a method which either returns an image from the cache, or returns a default image and starts a download.
步骤3:下载完成后,将图像添加到缓存中。然后找出哪些行需要图像。重新加载重新加载图像的所有行。
Step 3: When a download finishes, add the image to the cache. Then find out which rows need the image. Reload all the rows that reload the image.
下载应该使用GCD异步完成。我真的建议您将下载代码添加到单独的可重用方法中,以便您可以处理下载错误。即使你现在不这样做,你也会在以后再做。
The download should be done asynchronously using GCD. I would really recommend that you add the download code into a separate, reusable method so that you can handle download errors. Even if you don't do it now, you will do it later.
这篇关于在tableview中异步设置图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!