【问题标题】:Slow UITableView Scrolling from JSON从 JSON 滚动缓慢的 UITableView
【发布时间】:2014-12-02 00:43:19
【问题描述】:

当我从本地 JSON 加载时,我的 UITableView 滚动非常缓慢。正在从外部 URL 加载图像。我首先尝试在我的 viewWillAppear 方法中加载 JSON:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"HomePage" ofType:@"json"];
    NSError *error = nil;
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    self.titleLabels = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
});

在我的 tableView (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath 中,我有以下内容:

    HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];

if(cell == nil) {
    [tableView registerNib:[UINib nibWithNibName:@"HomeCell" bundle:nil] forCellReuseIdentifier:@"Cell"];
    cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
}

NSDictionary *titleLabels = [self.titleLabels objectAtIndex:indexPath.row];
NSString *label = [titleLabels objectForKey:@"Heading"];
NSURL *imageURL = [NSURL URLWithString:[titleLabels objectForKey:@"Image"]];

UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];

cell.label.text = label;
cell.imageView.image = image;
cell.cardView.frame = CGRectMake(10, 5, 300, 395);

return cell;

我只是想知道为什么表格视图滚动得很慢。如果有人能对此有所了解,将不胜感激。

谢谢!

【问题讨论】:

  • 这行UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]]; 导致了这个问题。这是来自主线程的同步调用,因此它会阻塞 UI,直到检索到图像数据。对图片使用延迟加载

标签: ios objective-c json uitableview


【解决方案1】:
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]]

这就是导致您的应用滚动缓慢的原因。您正在对 cell.imageView.image 属性进行网络调用。由于您在主线程上调用[UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];,因此应用程序需要等待网络调用完成,然后才能滚动更远。

这里的关键是,你在主线程上进行所有的网络调用,所有的触摸都会被延迟,直到所有的单元格都被完全加载。

完全不建议这样做。


更好的方法:

(1)。是进行网络呼叫,仅针对屏幕上的 VISIBLE CELLS。 按照本教程进行操作 --> RayWenderLich 的 How to Make Faster UITableViewCell Scrolling

(2)Apple's Sample Code, which shows this in action

(3) 预先加载所有图片,并在viewDidLoad之后存储在一个数组中

【讨论】:

  • 还有这个方便的库可以使用一次:github.com/rs/SDWebImage。当然,在阅读上面的链接后使用该库。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
  • 1970-01-01
  • 2013-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多