SDWebImage原始碼學習之由淺入深一
阿新 • • 發佈:2019-01-31
本次學習從SDWebImage 常用的圖片載入開始 ,由淺入深的剖析實現過程
UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
[imgV sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:nil];
首先進入方法 ,該方法是UIImageView 的分類中實現 UIImageView+WebCache.h
- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder {
[self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil];
}
繼續深入
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock {
// 此處為UIImageView 的父類UIView 的分類方法 UIView+WebCache
[self sd_internalSetImageWithURL:url
placeholderImage:placeholder
options:options
operationKey:nil
setImageBlock:nil
progress:progressBlock
completed:completedBlock];
}
檢視該方法詳細實現。分析見註釋
- (void)sd_internalSetImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
operationKey:(nullable NSString *)operationKey
setImageBlock:(nullable SDSetImageBlock)setImageBlock
progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock {
// 首先會根據operationKey 傳入的值來設定validOperationKey,當為nil時,設定為當前類名的字串
// 我們在呼叫 sd_setImageWithURL: placeholderImage: 時,這裡傳入的是nil 所以此處validOperationKey = @"UIImageView"
NSString *validOperationKey = operationKey ?: NSStringFromClass([self class]);
// 該方法將根據validOperationKey的值去取消對應的圖片載入任務
// 該方法的詳細實現在下面
[self sd_cancelImageLoadOperationWithKey:validOperationKey];
// 將當前url 通過imageURLKey 與self 繫結,由於self不同,這樣就實現了 url 與對應的UIImageView繫結。
objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
// 在本例的簡單呼叫中options = 0,所以 判斷為真,進入分支
// dispatch_main_async_safe() 這個巨集是為了判斷是否在主執行緒,如果不在則回到主執行緒呼叫。其實現見下
if (!(options & SDWebImageDelayPlaceholder)) {
dispatch_main_async_safe(^{
// 確保在主執行緒下呼叫
// 此處由引數可見 是為了先設定placeholder 即佔位圖,實現沒有圖片時顯示佔位圖,本例中 placeholder,setImageBlock 引數均為nil
// 該方法實現見下
[self sd_setImage:placeholder imageData:nil basedOnClassOrViaCustomSetImageBlock:setImageBlock];
});
}
if (url) {
// check if activityView is enabled or not
if ([self sd_showActivityIndicatorView]) {
[self sd_addActivityIndicator];
}
__weak __typeof(self)wself = self;
id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager loadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
__strong __typeof (wself) sself = wself;
[sself sd_removeActivityIndicator];
if (!sself) {
return;
}
dispatch_main_async_safe(^{
if (!sself) {
return;
}
if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) {
completedBlock(image, error, cacheType, url);
return;
} else if (image) {
[sself sd_setImage:image imageData:data basedOnClassOrViaCustomSetImageBlock:setImageBlock];
[sself sd_setNeedsLayout];
} else {
if ((options & SDWebImageDelayPlaceholder)) {
[sself sd_setImage:placeholder imageData:nil basedOnClassOrViaCustomSetImageBlock:setImageBlock];
[sself sd_setNeedsLayout];
}
}
if (completedBlock && finished) {
completedBlock(image, error, cacheType, url);
}
});
}];
[self sd_setImageLoadOperation:operation forKey:validOperationKey];
} else {
dispatch_main_async_safe(^{
[self sd_removeActivityIndicator];
if (completedBlock) {
NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
completedBlock(nil, error, SDImageCacheTypeNone, url);
}
});
}
}
dispatch_main_async_safe() 的實現,
dispatch_queue_get_label獲取當前佇列標籤,使用strcmp()函式和主執行緒佇列標籤比較
#ifndef dispatch_main_async_safe
#define dispatch_main_async_safe(block)\
if (strcmp(dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL), dispatch_queue_get_label(dispatch_get_main_queue())) == 0) {\
block();\
} else {\
dispatch_async(dispatch_get_main_queue(), block);\
}
#endif
該方法實現在UIView的分類UIView+WebCacheOperation
typedef NSMutableDictionary<NSString *, id> SDOperationsDictionary;
- (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key {
// Cancel in progress downloader from queue
SDOperationsDictionary *operationDictionary = [self operationDictionary];
id operations = operationDictionary[key];
if (operations) {
if ([operations isKindOfClass:[NSArray class]]) {
for (id <SDWebImageOperation> operation in operations) {
if (operation) {
[operation cancel];
}
}
} else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){
[(id<SDWebImageOperation>) operations cancel];
}
[operationDictionary removeObjectForKey:key];
}
}
- (SDOperationsDictionary *)operationDictionary {
// 通過變數繫結的方式,獲取到operations
SDOperationsDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey);
if (operations) {
return operations;
}
// 第一次進入時,operations需要新建立,並進行變數繫結給loadOperationKey,然後返回
operations = [NSMutableDictionary dictionary];
objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return operations;
}
- (void)sd_setImage:(UIImage *)image imageData:(NSData *)imageData basedOnClassOrViaCustomSetImageBlock:(SDSetImageBlock)setImageBlock {
if (setImageBlock) { // 本例中為nil
setImageBlock(image, imageData);
return;
}
// 下面程式碼就比較簡單了,根據self的類執行不同方法設定佔位圖。
#if SD_UIKIT || SD_MAC // 平臺相容適配巨集
if ([self isKindOfClass:[UIImageView class]]) {
UIImageView *imageView = (UIImageView *)self;
imageView.image = image;
}
#endif
#if SD_UIKIT
if ([self isKindOfClass:[UIButton class]]) {
UIButton *button = (UIButton *)self;
[button setImage:image forState:UIControlStateNormal];
}
#endif
}