2013-02-22 47 views
0

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

回答

2

我喜歡用AFNetworking library方便異步圖像加載。您將需要包括圖書館

#import "AFNetworking.h" 

然後在的cellForRowAtIndexPath

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

您還需要提供一個佔位符圖像使用它。我使用您想要最終圖像的大小的空白JPG。

1

作爲後續行動,這將是很好本地使用由傑克·馬什本非常方便的插件來緩存圖片:JMImageCache

這樣,圖像將不需要從下一次你的URL下載啓動應用程序。

2

您可以使用此鏈接中的SDWebImage:https://github.com/rs/SDWebImage 這是用於異步圖像加載的最簡單和最快的庫。 它還提供圖像緩存。 你只可以通過簡單地調用這個函數來完成整個操作:

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

只是享受它。

1

見,在所述的cellForRowAtIndexPath滯後是因爲該

NSURL * IMAGEURL =的[NSURL URLWithString:[calDict objectForKey:@ 「圖像」]];

NSData *imageData = [NSData dataWithContentsOfURL:imageURL]; 

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

你爲什麼不使用GCD添加圖像?此外,您可以讓自己的NSCache存儲圖像,以便每次重新加載表格時,都可以直接從內存中加載圖像,而不是點擊網址。