在開發信息流、應用商店這類列表頁面時,每個 cell 都掛著一張縮略圖,如果每次都直接走網絡,滑動體驗會非常糟糕。本文記錄一種在 cell 中下載圖片並做緩存優化的思路:先查內存,再查沙盒,最後才發起網絡請求,下載完成後同時寫入內存與磁碟。
以 app.icon 存放圖片地址為例,判斷順序如下:
imageView。Library/Caches 目錄下按文件名查找。命中則解碼顯示,並順手回填字典。NSOperationQueue,在子線程拉取數據。// app.icon 是圖片地址
// 1. 先從內存緩存中取出圖片
UIImage *image = self.images[app.icon];
if (image) {
// 內存命中,直接使用
cell.imageView.image = image;
} else {
// 2. 內存沒有,轉而查找沙盒
// 獲得 Library/Caches 文件夾
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
// 獲得文件名
NSString *filename = [app.icon lastPathComponent];
// 拼接出完整路徑
NSString *file = [cachesPath stringByAppendingPathComponent:filename];
// 讀取沙盒中的文件數據
NSData *data = [NSData dataWithContentsOfFile:file];
if (data) {
// 沙盒命中,直接解碼顯示
UIImage *image = [UIImage imageWithData:data];
cell.imageView.image = image;
// 回填內存緩存
self.images[app.icon] = image;
} else {
// 3. 兩級緩存都未命中,異步下載
[self.queue addOperationWithBlock:^{
// 子線程中下載
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:app.icon]];
UIImage *image = [UIImage imageWithData:data];
[NSThread sleepForTimeInterval:1.0]; // 模擬網絡延遲
// 回到主線程刷新界面
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
cell.imageView.image = image;
}];
// 寫入內存緩存
self.images[app.icon] = image;
// 寫入沙盒,下次直接命中磁碟緩存
[data writeToFile:file atomically:YES];
}];
}
}
上述代碼是最小可用版本,用於說清「內存 → 沙盒 → 網絡」三級查找的骨架。真正上線還需要補充:為隊列設置 maxConcurrentOperationCount 控制並發數量、在 cellForRow 復用時做 URL 比對避免圖片錯位、以及內存告警時清理字典。理解了三級緩存的順序,替換成 SDWebImage 這類成熟方案時也會更透徹。