【问题标题】:How to fix a slow scrolling table view如何修复滚动缓慢的表格视图
【发布时间】:2012-11-23 17:03:24
【问题描述】:

我有一个滚动缓慢的表格视图。有谁知道为什么会这样?

每一行都有一张图片,但即使在加载图片之后,它仍然会卡顿并缓慢滚动。

感谢您的帮助

这是我的代码:

- (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];
    }
    // Get item from tableData
    NSDictionary *item = (NSDictionary *)[displayItems objectAtIndex:indexPath.row];

    // display the youdeal deal image
    photoString = [item objectForKey:@"image"];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:photoString]]];

    cell.titleLabel.text = [item objectForKey:@"supercat"];
    cell.descriptionLabel.text = [item objectForKey:@"title"];

    NSString *convertedLeftCount = [NSString stringWithFormat:@"%@",[item objectForKey:@"left_count"]];

    cell.amountLabel.text = convertedLeftCount;

    cell.thumbnailImageView.image = image;
    cell.priceLabel.text = [item objectForKey:@"cat"];

    return cell;
}

【问题讨论】:

  • 使用异步方式加载图片

标签: objective-c ios uitableview tableview


【解决方案1】:

这是由于您使用的图像加载机制。

您正在从主线程中的 url 加载图像。这就是为什么 UI 被阻塞了一段时间,dataWithContentsOfURL: 也是一个同步调用。所以UI会在获取到图片数据后做出响应。

Apple 声明,像 webrequest、解析大数据等进程必须在其他线程上完成,而不是在主线程上完成。 并且所有与 UI 相关的任务都必须在主线程上完成。

解决方案:

  1. 在后台线程中请求图像,而不是在主线程中。
  2. 获取图像后对其进行缓存

源代码和第三方库

这里有一些链接可以帮助您了解使用异步方法加载图像的基本思想

  1. LazyTableImages
  2. HJCache
  3. SDWebImage

【讨论】:

  • 如果对 LazyTableImage 和 HJCache 有任何疑问,请咨询我
【解决方案2】:

每次加载单元格时都会加载图像,因为 imageWithData: 不使用任何缓存。

编辑:我看到一条评论建议异步加载图像。您已经为每个单元格提供了自定义类,因此应该很容易做到。如果这是一个答案,我会投票赞成

【讨论】:

    【解决方案3】:

    我想你是想说这个。

    NSURL* url = [NSURL URLWithString:@"http://www.YourImageUrl.com"];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    
    
    [NSURLConnection sendAsynchronousRequest:request
        queue:[NSOperationQueue mainQueue]
        completionHandler:^(NSURLResponse * response,
            NSData * data,
            NSError * error) {
    if (!error){
            UIImage* image = [[UIImage alloc] initWithData:data];
        // Now workout with the image
    }
    
    }];
    

    这将进行异步调用,并在 tableview 加载后加载图像,即当图像加载完成时,图像将显示,但在需要加载 tableview 时将加载表格。

    【讨论】:

      猜你喜欢
      • 2011-01-25
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多