Ios 从JSON缓慢滚动UITableView
从本地JSON加载时,UITableView的滚动速度非常慢。正在从外部URL加载图像。我首先尝试在我的ViewWillAspect方法中加载JSON:Ios 从JSON缓慢滚动UITableView,ios,objective-c,json,uitableview,Ios,Objective C,Json,Uitableview,从本地JSON加载时,UITableView的滚动速度非常慢。正在从外部URL加载图像。我首先尝试在我的ViewWillAspect方法中加载JSON: dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{ NSString *filePath = [[NSBundle mainBundle] pathForResource:@"HomePage" ofType:@"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]]
这就是导致应用程序中滚动速度慢的原因。您正在对cell.imageView.image属性进行网络调用。因为您正在调用[UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]]
在主线程上,应用程序需要等待网络调用完成,然后才能滚动更远
这里的关键点是,你正在主线程上进行所有的网络调用,所有的接触都会被延迟,直到所有的单元都被完全加载
根本不建议这样做
更好的方法: (1) 。是进行联网呼叫,仅针对屏幕上可见的单元格。 按照RayWenderLich的教程-->进行操作 (二)
(3) 在viewDidLoad之后,预先加载所有图像并将其存储在一个数组中此行
UIImage*image=[UIImage-imageWithData:[NSData-datawithcontentsofull:imageURL]]代码>导致问题。这是一个来自主线程的同步调用,因此它将阻塞UI,直到检索到图像数据。对图像使用延迟加载还有一个方便的库可以使用一次:。当然,在阅读了以上链接之后,请使用该库。