显示JSON数据的UITableView中的响应延迟

时间:2013-02-22 22:26:30

标签: ios json uitableview

在我的应用程序中,我正在解析JSON数据,然后在UITableView中显示该数据。信息显示在表格中,但触摸响应非常糟糕。我做了一些研究,发现建议对信息特别是图像实现异步加载,但我找不到任何适用于我的JSON应用程序的相关解决方案。我将不胜感激如何解决这个问题的一些建议和意见,这里是代码:

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

4 个答案:

答案 0 :(得分:2)

我喜欢使用AFNetworking library来轻松进行异步图像加载。您需要包含库

#import "AFNetworking.h"

然后在cellForRowAtIndexPath

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

您还需要提供占位符图像。我使用的是你想要最终图像的空白JPG。

答案 1 :(得分:2)

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

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

享受吧。

答案 2 :(得分:1)

作为后续工作,使用Jake Marsh这个非常方便的插件在本地缓存图像会很好:JMImageCache

这样,下次启动应用程序时,无需从URL加载图像。

答案 3 :(得分:1)

看,cellforRowAtIndexPath中的滞后是因为这个

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

NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

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

你为什么不使用GCD添加图片?您还可以拥有自己的NSCache来存储图像,这样每次表格重新加载时,图像都可以直接从内存加载而不是激活网址。