
本文為投稿文章,作者:missummer(簡書)
SDWebImage 是 iOS 開發者常用的開源框架,主要作用是:為 UIImageView 提供一個支持異步下載圖片並帶緩存的分類。動手分析前,先牢記緩存的三種類型:
typedef NS_ENUM(NSInteger, SDImageCacheType) { /** The image wasn't available the SDWebImage caches, but was downloaded from the web. 該圖像不在 SDWebImage 緩存中,而是從網絡下載的。 */ SDImageCacheTypeNone, /** The image was obtained from the disk cache. 圖像從磁盤緩存獲得。 */ SDImageCacheTypeDisk, /** The image was obtained from the memory cache. 圖像從內存緩存獲得。 */ SDImageCacheTypeMemory };UIImageView+WebCache
我們最常用的莫過於:
[_fineImageView sd_setImageWithURL:picURL placeholderImage:nil];
下面一步步看它的內部實現。這個方法最終會調用:
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock
查看 UIImageView+WebCache.h 會發現,官方提供了大量類似 sd_setImageWithURL:placeholderImage: 的方法,而它們最終都會彙聚到上面這個方法,它堪稱核心。首先執行的是:
// 移除 UIImageView 當前綁定的操作。當 TableView 的 cell 被重用時,先執行這行,確保該 ImageView 的下載與緩存組合操作都被取消 [self sd_cancelCurrentImageLoad];
看看它內部:
- (void)sd_cancelCurrentImageLoad { [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"]; }接著調用 UIView+WebCacheOperation 的 sd_cancelImageLoadOperationWithKey:。先看看這個分類提供了什麼:它為 UIView 提供了三個方法,用於操作綁定關係——sd_setImageLoadOperation:forKey:(設置加載操作)、sd_cancelImageLoadOperationWithKey:(取消當前 view 對應 key 的所有操作)、sd_removeImageLoadOperationWithKey:(僅移除而不取消)。
為了方便管理並找到視圖正在進行的操作,WebCacheOperation 把每個視圖實例與它正在進行的操作(下載 + 緩存的組合)綁定起來,實現操作與視圖一一對應,以便隨時取出並控制其取消。它用到了
objc_setAssociatedObject
objc_getAssociatedObject
NSObject+AssociatedObject 用 @dynamic 配合關聯對象,為已有類擴展出自定義屬性:
@implementation NSObject (AssociatedObject) @dynamic associatedObject; -(void)setAssociatedObject:(id)object{ objc_setAssociatedObject(self, @selector(associatedObject), object, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } -(id)associatedObject { return objc_getAssociatedObject(self, @selector(associatedObject)); }objc_setAssociatedObject 的作用是為已存在的類擴展添加自定義屬性,推薦把屬性 key 設為 static char 類型且唯一;objc_getAssociatedObject 則依 key 取出與對象綁定的屬性。operationDictionary 便是這樣把一個 NSMutableDictionary 綁定到視圖上,其 value 是操作、key 是針對不同視圖與操作設定的字符串:
- (NSMutableDictionary *)operationDictionary { NSMutableDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey); if (operations) { return operations; } operations = [NSMutableDictionary dictionary]; objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC); return operations; } - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key { NSMutableDictionary *operationDictionary = [self operationDictionary]; id operations = [operationDictionary objectForKey:key]; if (operations) { if ([operations isKindOfClass:[NSArray class]]) { for (id operation in operations) { if (operation) { [operation cancel]; } } } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){ [(id) operations cancel]; } [operationDictionary removeObjectForKey:key]; } }回到核心方法 sd_setImageWithURL:placeholderImage:options:progress:completed:,它開頭先取消當前加載,再把 url 作為關聯對象綁定到 ImageView 上(key 為 static char imageURLKey)。接著:
if (!(options & SDWebImageDelayPlaceholder)) { dispatch_main_async_safe(^{ self.image = placeholder; }); }這裡的 dispatch_main_async_safe 是個宏,用來保證 block 在主線程執行(因為圖像繪製只能在主線程完成)。若 url 存在,則可選地添加加載指示器,然後調用下載核心方法:
id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { [wself removeActivityIndicator]; if (!wself) return; dispatch_main_sync_safe(^{ if (!wself) return; // SDWebImageAvoidAutoSetImage:默認下載完自動設給 imageView,若設置此項則跳過自動賦值,交給 completionBlock 自行處理 if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) { completedBlock(image, error, cacheType, url); return; } else if (image) { wself.image = image; [wself setNeedsLayout]; } else { if ((options & SDWebImageDelayPlaceholder)) { wself.image = placeholder; [wself setNeedsLayout]; } } if (completedBlock && finished) { completedBlock(image, error, cacheType, url); } }); }]; [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"];下載完成後,會把新操作重新綁定到 ImageView 上(此前已 cancel 了舊操作)。若 url 不存在,則移除指示器並回調錯誤:
NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; completedBlock(nil, error, SDImageCacheTypeNone, url);SDWebImageManager
下載圖片的 downloadImageWithURL:options:progress:completed: 位於 SDWebImageManager。文檔對它的描述是:它是 UIImageView+WebCache 分類背後的核心,把異步下載器(SDWebImageDownloader)與圖片緩存(SDImageCache)聯繫起來。它的 downloadImageWithURL: 方法有幾個要點:第一個參數是圖片 url(若傳入 NSString 會自動轉為 NSURL,轉換失敗則置 nil 並停止);第二個 options 可定制各種行為;第三個 progressBlock 用於下載過程回調;第四個 completedBlock 在下載完成後回調;返回值是一個遵循 SDWebImageOperation 協議的 NSObject(即 SDWebImageDownloaderOperation),該協議只定義了 cancel 方法。
SDWebImageManager.m
初始化方法:
- (id)init { if ((self = [super init])) { _imageCache = [self createCache]; _imageDownloader = [SDWebImageDownloader sharedDownloader]; _failedURLs = [NSMutableSet new]; _runningOperations = [NSMutableArray new]; } return self; }它獲得 SDImageCache 與 SDWebImageDownloader 的單例,並用於存儲下載失敗 url 的數組,以及存儲下載 operation 的可枚舉數組。
利用 url 生成緩存 key 的 cacheKeyForURL: 會優先使用 cacheKeyFilter(一個返回字符串的 block),若為空則直接返回 url 的 absoluteString。
檢查圖片是否已緩存的方法 cachedImageExistsForURL: 先查內存緩存,命中即返回 YES,否則再查磁盤:
- (BOOL)cachedImageExistsForURL:(NSURL *)url { NSString *key = [self cacheKeyForURL:url]; if ([self.imageCache imageFromMemoryCacheForKey:key] != nil) return YES; return [self.imageCache diskImageExistsWithKey:key]; }另有兩個異步版本 cachedImageExistsForURL:completion: 與 diskImageExistsForURL:completion:,分別先查內存再查磁盤、以及只查磁盤,並都在主線程回調 block。
下面是 SDWebImageManager 的核心方法 downloadImageWithURL:,開頭先對 url 做類型校驗:
if ([url isKindOfClass:NSString.class]) { url = [NSURL URLWithString:(NSString *)url]; } if (![url isKindOfClass:NSURL.class]) { url = nil; }順帶說說 __block 與 __weak 的區別:__block 用於指明變量被 block 捕獲後仍可在 block 內修改(block 聲明時會截獲所用自動變量的值,默認只有使用權而無修改權),但 __block 不能避免循環引用,需在合適時手動置 nil;__weak 是所有權修飾符,本身可避免循環引用,但會導致外部對象釋放後 block 內無法訪問,可在 block 內用 __strong 變量指向 weak 對象以兼得兩者:
__block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new]; __weak SDWebImageCombinedOperation *weakOperation = operation;
SDWebImageCombinedOperation 什麼實質工作都不做,只保存兩樣東西:一個用於取消下載的 cancelBlock,以及一個負責下載並緩存的 cacheOperation。它遵循 SDWebImageOperation 協議,因此可作為返回值返回。其 cancel 會設置 cancelled 標記、取消 cacheOperation 並執行 cancelBlock(註釋中還提到為修復某 crash 而直接操作 ivar)。
@synchronized 是 OC 中便捷地創建互斥鎖的方式,可防止不同線程同時執行同一區塊代碼。self.failedURLs 是存放下載失敗 url 的 NSSet——之所以用 NSSet 而非 NSArray,是因為它基於 hash 查找、效率高,且天然不含重複元素。下載前會用互斥鎖判斷該 url 是否曾失敗:
BOOL isFailedUrl = NO; @synchronized (self.failedURLs) { isFailedUrl = [self.failedURLs containsObject:url]; } if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) { dispatch_main_sync_safe(^{ NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]; completedBlock(nil, error, SDImageCacheTypeNone, YES, url); }); return operation; }接著把 operation 加入 runningOperations(加鎖保護),並取得 key。後續邏輯會牽扯到越來越多類,建議先理清 NSOperation 再往下讀。核心是 queryDiskCacheForKey:done:——SDImageCache 中根據 key 異步查詢磁盤緩存的方法。它的 ioQueue 是一個串行隊列:
_ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL);該方法先查內存緩存,命中則直接 doneBlock 返回;否則在 ioQueue 中串行查磁盤,查到後(若開啟內存緩存)存入 memCache,最後在主線程回調 doneBlock:
- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock { if (!doneBlock) { return nil; } if (!key) { doneBlock(nil, SDImageCacheTypeNone); return nil; } UIImage *image = [self imageFromMemoryCacheForKey:key]; if (image) { doneBlock(image, SDImageCacheTypeMemory); return nil; } NSOperation *operation = [NSOperation new]; dispatch_async(self.ioQueue, ^{ if (operation.isCancelled) { return; } @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); }); } }); return operation; }回到 downloadImageWithURL:,它會把上面返回的緩存 operation 賦給組合操作的 cacheOperation,並在回調中判斷:若「緩存未命中或設置了 SDWebImageRefreshCached」且「代理允許下載」,則進行下載。下載時會把各種 SDWebImageOptions 映射為 downloaderOptions,再交給 imageDownloader。下載回調中會:判斷操作是否已取消(取消則不做任何事,避免與其他回調爭搶同一對象而覆蓋新數據);若出錯則回調並把 url 加入失敗列表(但超時、斷網、取消等錯誤不計入);若成功則按需進行圖片形變(調用代理的 imageManager:transformDownloadedImage:withURL:)並緩存,最後在主線程完成回調,並從 runningOperations 移除該組合操作。此外還設置了 cancelBlock,用於取消 subOperation 並從 runningOperations 移除自身。若緩存命中而無需下載,則直接完成回調並移除操作;若緩存未命中且代理不允許下載,則回調空結果。
總結
這個方法主要做了三件事:1. 創建一個 SDWebImageCombinedOperation 組合對象,負責對下載 operation 的創建與管理,同時兼具緩存功能,是下載與緩存兩個過程的組合;2. 先查內存與磁盤緩存(由 self.imageCache 的 queryDiskCacheForKey:done: 完成,其返回值即 cacheOperation),並在回調中依 SDWebImageRefreshCached 選項與代理是否允許下載來決定是否請求網絡,同時處理 NSURLCache、下載失敗與下載後緩存、以及可選的圖片形變;3. 把下載返回的操作命名為 subOperation,並在組合操作的 cancelBlock 中加入對其 cancel 的調用。至於「如何下載、如何緩存」的細節,我們留到下一篇再深入。