0

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

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

谢谢你的帮助

这是我的代码:

- (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;
}
4

3 回答 3

3

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

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

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

解决方案:

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

源代码和第三方库

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

  1. 懒表图像
  2. HJCache
  3. SDWebImage
于 2012-11-23T17:09:12.803 回答
2

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

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

于 2012-11-23T17:08:37.007 回答
0

我想你是想说这个。

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
}

}];

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

于 2013-10-18T11:35:09.523 回答