上一篇使用單執行緒下載圖片,容易讓主執行緒等待。本篇改用 NSOperationQueue,把下載工作放到背景佇列,並加入佔位圖與重複下載保護。

除了 apps 與 imgCache,還可增加 operations 字典與 queue。operations 用來記錄目前進行中的下載任務,避免同一張圖片被重複下載;queue 則負責控制並行數量。
@property (nonatomic, strong) NSMutableDictionary *operations; @property (nonatomic, strong) NSOperationQueue *queue;
- (NSOperationQueue *)queue {
if (!_queue) {
_queue = [[NSOperationQueue alloc] init];
_queue.maxConcurrentOperationCount = 3;
}
return _queue;
}
在 cellForRowAtIndexPath: 中,先檢查記憶體是否已有圖片。若沒有,再檢查沙盒。若沙盒也沒有,可先顯示佔位圖,然後建立 NSBlockOperation 下載。
NSOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:app.icon]];
if (data == nil) {
[self.operations removeObjectForKey:app.icon];
return;
}
UIImage *image = [UIImage imageWithData:data];
self.imgCache[app.icon] = image;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}];
[data writeToFile:file atomically:YES];
[self.operations removeObjectForKey:app.icon];
}];