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