我正在使用缓存图像但是当我在uitableview中向上滚动它会不断重新加载?

时间:2012-12-19 08:44:47

标签: ios xcode uitableview

我使用控制台检查它是否重新加载,并在cellForRowAtIndexPath中进行重新加载。它会导致表视图卡住一会儿。我认为这是因为图像,但现在我无法弄清楚问题。 任何帮助都会很棒。


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog( @"Cell loading" );
    static NSString *CellIdentifier = @"showVideo";
    CustomVideoCell *cell = (CustomVideoCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell=[[CustomVideoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    }


    NSURL *url = [NSURL URLWithString:[data objectForKey:@"profilepicture"]];
    NSData *data = [NSData dataWithContentsOfURL:url];

    [cell.playimage setImageWithURL:[NSURL URLWithString:[data objectForKey:@"profilepicture"]]
                 placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    return cell;

}

2 个答案:

答案 0 :(得分:3)

这一行提出了问题:

NSData *data = [NSData dataWithContentsOfURL:url];

这是一个同步调用,这就是滚动时感觉滞后的原因。

永远不要在主线程上调用此类方法,这会导致您的应用无响应。如果数据太高,那么下载需要更多时间,因此需要更多时间来回应UIEvents。

您需要在下载图像后缓存图像,否则每次重新加载图像时都会再次下载图像。如果图像已经下载,则需要从缓存中显示它,不要再次下载。您需要在cellForRowAtIndexPath上处理此问题。 您可以编写自己的代码来执行这些任务,也可以依赖以下示例。

检查以下库/源代码:

  1. HJCache
  2. LazyTableImages
  3. SDWebImage

答案 1 :(得分:0)

使用SDWebImage。它使得异步下载图像和管理缓存变得更加容易。