2013-10-17 45 views
0

我從JSON文件解析一些圖像和字符串,解析工作正常,但圖像加載速度非常慢。我注意到,當我按下UITableViewCell時,UITableView顯示內容更快。有誰知道這個問題的解決方法?UITableViewCell數據加載錯誤

這裏是我使用的代碼,我使用NSOperationQueue來保持CPU使用率低。

NSDictionary *dict; 
    dict = [application objectAtIndex:indexPath.row]; 

    name = [dict objectForKey:@"name"]; 
    detileName = [dict objectForKey:@"detailName"]; 
    itmsLink = [dict objectForKey:@"itms-serviceLink"]; 
    icon = [dict objectForKey:@"icon"]; 
    developer = [dict objectForKey:@"developer"]; 
    version = [dict objectForKey:@"version"]; 
    category = [dict objectForKey:@"category"]; 
    rating = [dict objectForKey:@"rating"]; 
    ratingNumbers = [dict objectForKey:@"ratingNumber"]; 
    description = [dict objectForKey:@"description"]; 
    developerEmails = [dict objectForKey:@"developerEmail"]; 

    [downloadQueue addOperationWithBlock:^{ 

     cell.AppName.text = name; 
     cell.category.text = category; 
     cell.rater.text = [NSString stringWithFormat:@"(%@)", ratingNumbers]; 
     if ([rating intValue] == 1) { 
      cell.rating.image = [UIImage imageNamed:@"1.png"]; 
     } 
     if ([rating intValue] == 2) { 
      cell.rating.image = [UIImage imageNamed:@"2.png"]; 
     } 
     if ([rating intValue] == 3) { 
      cell.rating.image = [UIImage imageNamed:@"3.png"]; 
     } 
     if ([rating intValue] == 4) { 
      cell.rating.image = [UIImage imageNamed:@"4.png"]; 
     } 
     cell.itms = itmsLink; 
     cell.AppIcon.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:icon]]]; 
     cell.number.text = [NSString stringWithFormat:@"%li", (long)indexPath.row + 1]; 
    }]; 

回答

0

看起來你已經有了大部分的數據需要存在於細胞,除了圖像將在AppIcon.image去。現在設置的方式,圖像下載阻止您立即呈現單元格。我的猜測是圖像下載最終會完成,但是在下載完成後你不會強制單元重繪。在單元格上敲擊會迫使它重新繪製自己,這可能是爲什麼你看到了你描述的行爲。

我建議您立即使用您已經下載的數據展示這個單元格,然後啓動圖像的後臺下載。下載完成後,您可以發送NSNotification並更新適當的單元。你可以通過創建NSOperation的一個子類,在初始化過程中接受一個URL,然後將該操作添加到你的操作隊列中。如果你不想自己做所有的工作,那麼UIImageView上有一個類別使用AFNetworking爲您使用塊進行更新。 https://github.com/zbowling/AFNetworkingPollTest/blob/master/ServerTest/UIImageView%2BAFNetworking.h

0

如前所述的@Nick Galasso - 你不刷新細胞的和單元格指針傳遞給一個塊是一個非常不好的做法,因爲UITableView實際上重用細胞的,當下載完成後,你應該重新獲取單元格指針 - 您對實際NSIndexPath下的單元格感興趣,而不是對象。

下一個環節: https://developer.apple.com/library/ios/samplecode/LazyTableImages/Introduction/Intro.html

你可以找到懶圖像加載完美示例代碼,片段下方顯示這實際上帶來的視圖的一部分,該代碼調用設定下載完成的圖像儘快:

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath]; 
cell.imageView.image = downloadedImage; 

你可以在下載類的一些完成處理程序中調用它(Apple鏈接下的示例覆蓋那個)。