0

在我的应用程序中,我正在解析 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

4 回答 4

2

我喜欢使用AFNetworking 库来轻松进行异步图像加载。您将需要包括图书馆

#import "AFNetworking.h"

然后在 cellForRowAtIndexPath 中使用它

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

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

于 2013-02-22T22:37:30.530 回答
2

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

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

尽情享受吧。

于 2013-02-23T04:14:51.817 回答
1

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

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

于 2013-02-22T22:57:27.947 回答
1

看, cellforRowAtIndexPath 的滞后是因为这个

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

NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

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

你为什么不使用 GCD 添加图像?此外,您可以拥有自己的 NSCache 来存储图像,以便每次重新加载表时,都可以直接从内存中加载图像,而不是触发 url。

于 2014-05-30T04:50:30.887 回答