2015-01-26 55 views
-1

我有一個UITableView在滾動期間變得非常滯後。 的圖像保存在一個陣列從JSON(在viewDidLoad中)和我在的cellForRowAtIndexPath圖片代碼:滾動時UITableView是laggy

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
static NSString *simpleTableIdentifier = @"UserDiscountsTableViewCell"; 

UserDiscountsTableViewCell *cell = (UserDiscountsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 


if (cell == nil) { 
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"UserDiscountsTableViewCell" owner:self options:nil]; 
    cell = [nib objectAtIndex:0]; 
} 


cell.userDiscountNameLabel.text = [userDiscountName objectAtIndex:indexPath.row]; 

cell.userDiscountImages.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[userDiscountImages objectAtIndex:indexPath.row]]]]; 


return cell; 

}

我使用的是自定義的UITableViewCell。當我用cell.userDiscountImages.image刪除部分代碼時,一切都很完美。

任何人都可以提出什麼可能是laggy滾動的原因?

回答

1

你回答了你的問題,你自己:如果你刪除了你設定的形象路線,一切工作正常。該行需要花費大量時間來處理,並且您在主線程中執行該操作,從而阻止用戶界面。

嘗試使用Grand Central Dispatch將圖像初始化發送到後臺線程。初始化完成後,您需要返回主線程,然後可以執行UI更新。這將是這個樣子:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

    UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[userDiscountImages objectAtIndex:indexPath.row]]]]; 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     UserDiscountsTableViewCell *discountCell = (UserDiscountsTableViewCell *)[tableView cellForRowAtIndexPath:indexPath]; 
     discountCell.userDiscountImages.image = img 
    }); 
}); 

注意,初始化圖像後,我沒有直接設置它的電池,我把它抓回來從UITableView:這是因爲在圖像已加載的時間,該單元可能已被重新用於在另一個NSIndexPath處顯示另一個單元。如果你不這樣做,你可能會在錯誤的單元格中顯示錯誤的圖像。

+0

非常感謝!它完美的作品。 – user3686588 2015-01-26 19:36:40