遇見你之前,我只有眼前的茍且,遇見你之后,才有了詩和遠(yuǎn)方。
話不多說,我們最熟悉的
sd_setImageWithURL:placeholderImage:
或sd_setImageWithURL:placeholderImage:options:
,會(huì)先把placeholderImage
顯示,然后SDWebImageManager
根據(jù)URL處理圖片。進(jìn)入
SDWebImageManager-downloadWithURL:options:progress:completed:
,交給SDImageCache
從緩存查找圖片是否已經(jīng)下載queryDiskCacheForKey:done:
先從內(nèi)存圖片緩存查找是否有圖片,源碼:
UIImage *image = [self imageFromMemoryCacheForKey:key];
if (image) {
doneBlock(image, SDImageCacheTypeMemory);
return nil;
}
如果內(nèi)存中已經(jīng)有圖片緩存,SDImageCache
回調(diào) SDWebImageQueryCompletedBlock()
到 SDWebImageManager
。
SDWebImageCompletionBlock
回調(diào)SDWebImageCompletionWithFinishedBlock
到UIImageView+WebCache
等前端展示圖片。如果內(nèi)存緩存中沒有,開啟異步線程從硬盤查找圖片是否已經(jīng)緩存。根據(jù) URLKey 在硬盤緩存目錄下嘗試讀取圖片文件。源碼:
@autoreleasepool {
UIImage *diskImage = [self diskImageForKey:key];
if (diskImage && self.shouldCacheImagesInMemory) {
NSUInteger cost = SDCacheCostForImage(diskImage);
[self.memCache setObject:diskImage forKey:key cost:cost];
}
dispatch_async(dispatch_get_main_queue(), ^{
doneBlock(diskImage, SDImageCacheTypeDisk);
});
}
如果上一操作從硬盤讀取到了圖片,將圖片添加到內(nèi)存緩存中(如果空閑內(nèi)存過小,會(huì)先清空內(nèi)存緩存)。SDImageCache
回調(diào) SDWebImageQueryCompletedBlock
,進(jìn)而回調(diào)展示圖片。
如果從硬盤緩存目錄讀取不到圖片,說明所有緩存都不存在該圖片,需要下載圖片,重新生成一個(gè)下載器
SDWebImageDownloader
開始下載圖片。圖片下載由
NSMutableURLRequest
來做,實(shí)現(xiàn)相關(guān)block來判斷圖片下載中、下載完成和下載失敗。至于下載后圖片如何處理,解碼等并未研究,一旦圖片解碼完成,相關(guān)block回調(diào),得到downloadedImage,回調(diào)給需要的地方展示圖片。將圖片保存到 SDImageCache 中,內(nèi)存緩存和硬盤緩存同時(shí)保存。
SDImageCache
在初始化的時(shí)候會(huì)注冊一些消息通知,在內(nèi)存警告或退到后臺(tái)的時(shí)候清理內(nèi)存圖片緩存,應(yīng)用結(jié)束的時(shí)候清理過期圖片。
10.緩存大小與清除
NSInteger size = [[SDImageCache sharedImageCache] getSize];
[[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
NSLog(@"清除成功");
}];