原文:Advanced issues: Asynchronous UITableViewCell content loading done right
有什么問題?
你是否經常好奇,為什么你UITableView的加載往往“幾乎”是完美的?我的意思是,你已經明確地告訴了iOS,所有單元格的工作(例如從遠程URL加載圖片或者渲染內容)都要在后臺線程中異步地完成計算。但是有時候這還不夠,主要有兩個原因:
- 當一個cell離開了可見區域時,你所調用的異步操作仍然在工作。這通常會造成不必要的對系統資源的使用,甚至會由不知道哪個cell完成的異步任務返回而產生bug般的結果。
- UITableViewCells通常是被復用的實例。也就是說被加載到view的cell所持有的數據原本是屬于另一個完全不同的cell的。這常常會造成一種令人沮喪的,被稱作“Cell switching"的bug。
問題解決啦!
首先,你要明白解決這個問題的方法有很多——有些非常好,而有些則,呃,很惡心。我接下來準備介紹的方法基于一個Apple提供的demo(WWDC 2012 session 211),你知道的,這些家伙非常精通iOS。
在我們的例子里,我將使用一個簡單的UITableView實例,用于顯示你的Facebook好友的名字和資料照片。核心思路是:我們需要在UITableViewDataSource的tableView:cellForRowAtIndexPath:代理方法被調用時加載資料照片。如果操作成功,并且該cell依然在view當中,我們就簡單地把圖片添加到cell里用于顯示詳情照片的image view即可。(這一操作需要在主線程中完成)。否則的話,我們要確保我們并沒有執行setImage操作。
在開始之前,有一些準備工作:為后臺運行的operations定義一個NSOperationQueue,我們在這里稱之為imageLoadingOperationQueue。同樣的,為存儲指向特定operations的引用對象們定義一個NSMutableDictionary——在這個示例中我們將為Facebook的唯一id和oprations對象在facebookUidToImageDownloadOperations字典建立map映射。
最重要的部分已經寫在代碼注釋中,看完注釋你就明白了:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
FacebookFriend *friend = [self.facebookFriends objectAtIndex:indexPath.row];
FacebookFriendCell *cell = [tableView dequeueReusableCellWithIdentifier:FB_CELL_IDENTIFIER forIndexPath:indexPath];
cell.lblName.text = friend.name;
//為加載圖片到資料image view的操作創建一個block operation
NSBlockOperation *loadImageIntoCellOp = [[NSBlockOperation alloc] init];
//定義一個weak operation,以便在block內引用而不用產生引用循環
__weak NSBlockOperation *weakOp = loadImageIntoCellOp;
[loadImageIntoCellOp addExecutionBlock:^(void){
//一些異步任務。一旦Image下載完成,它將會在主線程被加載到view當中
UIImage *profileImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:friend.imageUrl]]];
[[NSOperationQueue mainQueue] addOperationWithBlock:^(void) {
//在執行操作前檢查操作是否已經取消。我們使用cellForRowAtIndexPath來確保對于不可見cell會返回nil
if (!weakOp.isCancelled) {
FacebookFriendCell *theCell = (FacebookFriendCell *)[tableView cellForRowAtIndexPath:indexPath];
[theCell.ivProfile setImage:profileImage];
[self.facebookUidToImageDownloadOperations removeObjectForKey:friend.uid];
}
}];
}];
//在NSMutableDictionary中保存一個指向operation的引用,以便稍后可以取消
if (friend.uid) {
[self.facebookUidToImageDownloadOperations setObject:loadImageIntoCellOp forKey:friend.uid];
}
//將operation添加到指定的后臺隊列
if (loadImageIntoCellOp) {
[self.imageLoadingOperationQueue addOperation:loadImageIntoCellOp];
}
//確保cell不會持有任何來自重用的數據的痕跡-
//這里是一個assign placeholder的好地方
cell.ivProfile.image = nil;
return cell;
}
現在剩下的事情就是利用iOS 6.0中引入的新的UITableViewDelegate方法:tableView:didEndDisplayingCell:forRowAtIndexPath:,在我們不再需要加載數據到單元格時調用它。
下面的代碼似乎是獲取相關的operation并且取消它的最佳位置:
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
FacebookFriend *friend = [self.facebookFriends objectAtIndex:indexPath.row];
//Fetch operation that doesn't need executing anymore
NSBlockOperation *ongoingDownloadOperation = [self.facebookUidToImageDownloadOperations objectForKey:friend.uid];
if (ongoingDownloadOperation) {
//Cancel operation and remove from dictionary
[ongoingDownloadOperation cancel];
[self.facebookUidToImageDownloadOperations removeObjectForKey:friend.uid];
}
}
同樣的,當table不再被需要時,不要忘記利用*** NSOperationQueue 并且調用cancelAllOperations***:
- (void)viewDidDisappear:(BOOL)animated {
[self.imageLoadingOperationQueue cancelAllOperations];
}
搞定!現在你自己也擁有了流暢如法拉利般的UITableView啦,不用謝~