網路圖片列表是每個 iOS 工程師都寫過的功能,但要把細節處理好其實不容易:快取怎麼做、cell 重用造成圖片錯亂怎麼辦、使用者快速滑動導致重複下載怎麼辦、圖片抓不到導致字典寫入崩潰怎麼辦。這篇我們把 SDWebImage 的核心思路手刻一遍,用 NSOperation 與二級快取把這些問題一次解決。
最直覺的做法是只用一個字典做內存快取。但 App 一重啟,內存快取就空了,所有圖片都要重新下載。因此實務上會做成二級快取:
查詢順序
#import "ViewController.h"
#import "WZYApp.h"
@interface ViewController ()
@property (nonatomic, strong) NSArray *apps; // 資料模型陣列
@property (nonatomic, strong) NSMutableDictionary *operations; // 保存操作物件,避免重複建立
@property (nonatomic, strong) NSMutableDictionary *images; // 內存快取
@property (nonatomic, strong) NSOperationQueue *queue; // 操作隊列
@end
@implementation ViewController
#pragma mark - 懶加載
- (NSMutableDictionary *)operations {
if (_operations == nil) {
_operations = [NSMutableDictionary dictionary];
}
return _operations;
}
- (NSOperationQueue *)queue {
if (_queue == nil) {
_queue = [[NSOperationQueue alloc] init];
}
return _queue;
}
- (NSMutableDictionary *)images {
if (_images == nil) {
_images = [NSMutableDictionary dictionary];
}
return _images;
}
- (NSArray *)apps {
if (_apps == nil) {
// 讀取 plist
NSArray *array = [NSArray arrayWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:@"apps.plist" ofType:nil]];
// 字典陣列 → 模型陣列
NSMutableArray *arrayM = [NSMutableArray array];
for (NSDictionary *dict in array) {
[arrayM addObject:[WZYApp appWithDict:dict]];
}
_apps = arrayM;
}
return _apps;
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.apps.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ID = @"app";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
WZYApp *appM = self.apps[indexPath.row];
cell.textLabel.text = appM.name;
cell.detailTextLabel.text = appM.download;
// 先查內存快取
UIImage *image = [self.images objectForKey:appM.icon];
if (image) {
cell.imageView.image = image;
} else {
// 內存沒有,改查磁碟快取
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *fileName = [appM.icon lastPathComponent]; // 取 URL 最後一個節點,含副檔名
NSString *fullPath = [caches stringByAppendingPathComponent:fileName];
NSData *data = [NSData dataWithContentsOfFile:fullPath];
if (data) {
// 磁碟有:直接顯示,並回填內存快取
UIImage *diskImage = [UIImage imageWithData:data];
cell.imageView.image = diskImage;
[self.images setObject:diskImage forKey:appM.icon];
} else {
// 兩層快取都沒有,才真的下載
// 問題一:cell 重用導致圖片錯亂
// 解法:先設佔位圖,不要設 nil(否則網路差時使用者會以為圖片不存在)
cell.imageView.image = [UIImage imageNamed:@"Snip20160712_43"];
// 問題二:使用者來回滑動造成重複下載
// 解法:用字典檢查該圖的下載操作是否已存在
NSBlockOperation *download = [self.operations objectForKey:appM.icon];
if (download == nil) {
NSBlockOperation *download = [NSBlockOperation blockOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:appM.icon];
// 這裡刻意加上空轉迴圈,模擬網路不佳時下載耗時
for (NSInteger i = 0; i < 1000000000; i++) {}
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
if (image == nil) {
// 問題三:nil 不能存進字典,否則會崩潰
// 同時處理「網路中斷後恢復」的情境:
// 若這次失敗,就把操作從字典移除,下次滑到才會重新建立下載
[self.operations removeObjectForKey:appM.icon];
return;
}
// 寫入兩層快取
[self.images setObject:image forKey:appM.icon];
[data writeToFile:fullPath atomically:YES];
// 問題四:非同步下載,回到主線程才不會來不及設定就 return cell
// 解法:只刷新該列,不要 reloadData 整個表
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[tableView reloadRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationFade];
}];
}];
// 把操作存起來,避免重複建立
[self.operations setObject:download forKey:appM.icon];
// 加入隊列,在子執行緒執行,避免 UI 卡頓
[self.queue addOperation:download];
} else {
// 操作已存在,代表正在下載,等就好
NSLog(@"%zd 行的圖片正在下載,請等待....", indexPath.row);
}
}
}
return cell;
}
@end
上面這一百多行,考慮到的情況仍然有限。實務上直接用 SDWebImage 就好——它內部還處理了許多我們一時想不到的邊界狀況,一行就能取代整段邏輯:
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:appM.icon]
placeholderImage:[UIImage imageNamed:@"Snip20160712_43"]];
一個要注意的細節:在 tableView 上直接用 SDWebImage 設定 image 時,如果 imageView 的尺寸沒有事先確定,可能會出現顯示異常。因此建議自訂 cell,並在建立時就把 imageView 的 frame 固定好。SDWebImage 是通用框架,服務的場合不只 tableView,這個問題作者的回應也是相同的方向。

手刻一遍的意義不在於日後真的自己寫,而在於理解 SDWebImage 背後在做什麼:兩層快取的查詢順序、以操作字典去重、主線程回刷、失敗重試。懂這些之後,遇到快取相關的效能或顯示問題,你才知道該往哪裡查。