2014-12-02 376 views
1

當我從本地JSON加載時,我的UITableView滾動真的很慢。圖像正在從外部URL加載。我第一次嘗試在我的viewWillAppear中的方法加載JSON:從JSON慢速UITableView滾動

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{ 
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"HomePage" ofType:@"json"]; 
    NSError *error = nil; 
    NSData *data = [NSData dataWithContentsOfFile:filePath]; 
    self.titleLabels = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
}); 

而且在我的tableView(定義UITableViewCell *)的tableView:(UITableView的*)的tableView的cellForRowAtIndexPath,我有以下幾點:

HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; 

if(cell == nil) { 
    [tableView registerNib:[UINib nibWithNibName:@"HomeCell" bundle:nil] forCellReuseIdentifier:@"Cell"]; 
    cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; 
} 

NSDictionary *titleLabels = [self.titleLabels objectAtIndex:indexPath.row]; 
NSString *label = [titleLabels objectForKey:@"Heading"]; 
NSURL *imageURL = [NSURL URLWithString:[titleLabels objectForKey:@"Image"]]; 

UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]]; 

cell.label.text = label; 
cell.imageView.image = image; 
cell.cardView.frame = CGRectMake(10, 5, 300, 395); 

return cell; 

我只是想知道爲什麼表格視圖滾動非常緩慢。如果任何人都可以對此有所瞭解,將不勝感激。

謝謝!

+1

此行'的UIImage *圖像= [ UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];'會導致問題。這是來自主線程的同步調用,所以它會阻塞用戶界面,直到檢索到圖像數據。使用延遲加載的圖像 – 2014-12-02 00:47:30

回答

2
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]] 

這是什麼導致您的應用程序緩慢滾動。您正在爲cell.imageView.image屬性進行網絡調用。由於您在主線程中調用[UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];,因此該應用程序需要等待網絡呼叫完成,纔可以進一步滾動。

這裏的關鍵是,你正在做主線程上的所有網絡調用,並且所有的觸摸都會延遲,直到所有的單元都被完全加載。

完全不推薦這樣做。


更好的方法:

(1)。是爲了進行網絡通話,只爲屏幕上的VISIBLE CELLS。 按照本教程 - >How to Make Faster UITableViewCell Scrolling通過RayWenderLich

(2)Apple's Sample Code, which shows this in action

(3)預先加載的所有圖像和它,存儲在數組中viewDidLoad中後

+0

還有一個方便的庫可以使用一次:https://github.com/rs/SDWebImage。當然,在閱讀上面的鏈接後使用庫。 – levibostian 2015-12-03 03:15:08