从sd_setImageWithURL:方法谈SDWebImage (一)

SDWebImage是GitHub上耳熟能详的iOS网络图片下载三方库。在iOS 中图片下载使用最多的方法应该是sd_setImageWithURL:,仅仅一个方法就可以开启异步下载、合理缓存机制。
SDWebImage中最常用的方法如下:

#import "UIImageView+WebCache.h" // 导入UIImageView的分类

UIImageView *avatar = [UIImageView new];
// 调起SDWebImage的下载代码
[avatar sd_setImageWithURL:[NSURL URLWithString:imageURL]];

上诉代码就能够直接从网络上下载图片并且显示。接下来我们从UIImageView+WebCache的sd_setImageWithURL:方法开始一步一步的来了解SDWebImage。
UIImageView+WebCache是SDWebImage为常用的UIKit做的扩展之一。其它的WebCache Categories主要包含

#import "NSImage+WebCache.h" // Mac开发 使用
#import "MKAnnotationView+WebCache.h"
#import "UIButton+WebCache.h"
#import "UIImageView+HighlightedWebCache.h"
#import "UIImageView+WebCache.h"
#import "UIView+WebCache.h"

以UIView+WebCache.h作为基础的Category封装了最基础功能:图片下载、取消下载。其它的Category根据自身的特点扩展了更多便利的方法但各自实现的方法最终都是调用到UIView+WebCache来进行图片下载,本文只拿出UIView+WebCache来进行分析,其它Category都是对UIView+WebCache的扩展使用。

UIView+WebCache中的核心方法只有一个:

- (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;

UIView+WebCache.m下载的实现,我去除了一些代码,保留了重要的下载代码如下:


- (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 {
    // 取消之前得下载操作
    NSString *validOperationKey = operationKey ?: NSStringFromClass([self class]);
    [self sd_cancelImageLoadOperationWithKey:validOperationKey];
    // 动态绑定imageURLKey,用来存储和返回下载图片的地址
    objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    if (url) {  // 判断url是否有效
      // 开启下载任务,返回下载的operation
        __weak __typeof(self)wself = self;
        // 构建图片下载的operation(需遵守SDWebImageOperation协议,用于取消operation)
        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;
            dispatch_main_async_safe(^{
                if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) {  
                     // options设置了不自动 调用Set图片的策略时直接回调结果
                    completedBlock(image, error, cacheType, url);
                    return;
                } else if (image) {
                    // 自动设置图片。(内部会做判断设置UIImage的图片、UIButton不同状态的图片和背景图等)
                    [sself sd_setImage:image imageData:data basedOnClassOrViaCustomSetImageBlock:setImageBlock];
                    [sself sd_setNeedsLayout];
                } else {
                }
              //  结果的回调,包含图片、错误、缓存类型、及图片
                if (completedBlock && finished) {
                    completedBlock(image, error, cacheType, url);
                }
            });
        }];
        // 由于异步下载图片,根据validOperationKey存储图片下载操作,以备图片下载未完成之时用来取消operation
        [self sd_setImageLoadOperation:operation forKey:validOperationKey];
    } else { 
      // 直接回调失败
    }
}

需要注意的地方:

dispatch_main_async_safe(); 是作者用来确保在主线程执行代码的宏定义,之前使用[NSThread mainThread]来判断,现在版本使用
使用strcmp来判断dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL),dispatch_queue_get_label(dispatch_get_main_queue() 是否相等

使用关联对象为UIView增加图片URL
objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_getAssociatedObject(self, &imageURLKey);

接下来让我们一行行的看下代码。
首先,取消之前下载操作

    //  取得一个下载操作key(nil,用类名做key)
    NSString *validOperationKey = operationKey ?: NSStringFromClass([self class]);
    // 取消下载
    [self sd_cancelImageLoadOperationWithKey:validOperationKey];

sd_cancelImageLoadOperationWithKey:方法是在一个新的分类
在UIView+WebCacheOperation中:

UIView+WebCacheOperation.h

- sd_setImageLoadOperation:forKey:
- sd_cancelImageLoadOperationWithKey:
- sd_removeImageLoadOperationWithKey:

在UIView+WebCacheOperation.h的API都是对下载operation的操作。绑定operation、取消operation、移除operation。在UIView+WebCacheOperation.m同样使用关联对象针对每个UIKit对象在内存中维护一个字典operationDictionary。可以对不同的key值添加对应的下载operation,也可以在下载操作没有完成的时候根据key取到operation进行取消。在这里作者将不同的功能方法放在不同的Category中,便于管理区分。

operationDictionary的key一般是类名,如此同一个UIImageView同时调用两次,第一次的下载操作会先被取消,然后将operationDictionary的中的operation对应到第二次的下载操作。针对特殊情况作者也做了修改(如按钮不同状态下的图片key值是添加了状态的枚举值的字符串区分,所以按钮可以同时开启多个图片下载任务)对开发人员一般不需要配置。

- (SDOperationsDictionary *)operationDictionary {
    SDOperationsDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey);
    if (operations) {
        return operations;
    }
    operations = [NSMutableDictionary dictionary];
    objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    return operations;
}
  • 目前我们大概了解了SDWebImage的下载的过程:从sd_setImageWithURL开始—>sd_internalSetImageWithURL:—>SDWebImageManager.sharedManager开启异步下载同时返回一个下载任务operation,以key:operation形式存放到UIView的关联对象(operationDictionary字典)中。以后可根据key取出对应的operation进行取消等操作——>图片异步下载成功or失败,根据设置的options策略赋值图片到相应的UI控件上。

  • 每个UIView的控件SDWebimage都用关联对象的方式在UIView+WebCache中绑定了一个imageURL,在UIView+WebCacheOperation中绑定了用于存放下载图片operation的字典operationDictionary。


以上,可以看出图片下载开始前和完成后的代码逻辑。
而图片下载关键在SDWebImageManager.sharedManager的loadImageWithURL:的方法。下篇文章谈谈SDWebImageManager又是如何下载图片!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容