显示JSON数据的UITableView中的响应滞后

问题描述:

在我的应用程序中,我正在解析JSON数据,然后在UITableView中显示该数据。信息显示在表格中,但触摸响应相当滞后。我做了一些研究,发现建议为信息和特别是图像实现异步加载,但是我找不到与我的JSON应用程序一起工作的任何相关解决方案。我希望得到一些建议,如何来解决这个问题的意见,这里是代码:显示JSON数据的UITableView中的响应滞后

jURL定义www.website.com/info.json

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    dispatch_async(jQueue, ^{ 

     NSData* data = [NSData dataWithContentsOfURL: 

         jURL]; 

     [self performSelectorOnMainThread:@selector(fetchedData:) 

           withObject:data waitUntilDone:NO]; 

    }); 

} 



- (void)fetchedData:(NSData *)responseData { 
    NSError* error; 

    NSDictionary* jsonDict = [NSJSONSerialization 

          JSONObjectWithData:responseData 

          options:kNilOptions 

          error:&error]; 

    calRes = [jsonDict objectForKey:@"results"]; 

    [self.tableView reloadData]; 

} 



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    NSDictionary *calDict = [calRes objectAtIndex:indexPath.row]; 

    NSURL *imageURL = [NSURL URLWithString:[calDict objectForKey:@"image"]]; 

    NSData *imageData = [NSData dataWithContentsOfURL:imageURL]; 

    UIImage *imageLoad = [[UIImage alloc] initWithData:imageData]; 

    cell.textLabel.text = [calDict objectForKey:@"name"]; 

    cell.detailTextLabel.text = [calDict objectForKey:@"description"];  
    cell.imageView.image = imageLoad; 

    return cell; 
} 
+2

滞后由方法'cellForRowAtIndexPath'内的图像下载给出,请看一下[this project](https://github.com/rs/SDWebImage)以异步方式下载图像 – tkanzakic 2013-02-22 22:35:00

我喜欢用AFNetworking library方便异步图像加载。您将需要包括图书馆

#import "AFNetworking.h" 

然后在的cellForRowAtIndexPath

[cell.imageView setImageWithURL:[NSURL URLWithString:[calDict objectForKey:@"image"]] 
    placeholderImage:[UIImage imageNamed:@"placeholder"]]; 

您还需要提供一个占位符图像使用它。我使用您想要最终图像的大小的空白JPG。

作为后续行动,这将是很好本地使用由杰克·马什本非常方便的插件来缓存图片:JMImageCache

这样,图像将不需要从下一次你的URL下载启动应用程序。

您可以使用此链接中的SDWebImage:https://github.com/rs/SDWebImage 这是用于异步图像加载的最简单和最快的库。 它还提供图像缓存。 你只可以通过简单地调用这个函数来完成整个操作:

[cell.imageView setImageWithURL:jURL 
        placeholderImage:[UIImage imageNamed:@"your place holder here"]]; 

只是享受它。

见,在所述的cellForRowAtIndexPath滞后是因为该

NSURL * IMAGEURL =的[NSURL URLWithString:[calDict objectForKey:@ “图像”]];

NSData *imageData = [NSData dataWithContentsOfURL:imageURL]; 

UIImage *imageLoad = [[UIImage alloc] initWithData:imageData]; 

你为什么不使用GCD添加图像?此外,您可以让自己的NSCache存储图像,以便每次重新加载表格时,都可以直接从内存中加载图像,而不是点击网址。