SDWebImage源码分析(一)- 下载器实现
一、从加载一张图开始梳理


VS AFNetworking

相对AFNetworking来讲,SDWebImage使用起来稍显晦涩一些,没有AFN那么直接
(一)更直接一些,set一张高清图片
image.png
sd_setImageWithURL
一步步进入源码 其实就是一个使用由简单到高阶的选择而已
其实可以选择不同复杂度的api使用 选择简单实用方式,内部默认使用的还是复杂api,只是参数自动补充nil而已:
image.png
image.png
imageCache 通过SDWebImageaManager获取,与AFNetworking cache不同的是,AFN的cache是通过下载器获取的,不是放在所谓的manager中
与AFN一样的是,ImageCache都是协议
(二)分析WebCache下载器
- 从第一次加载图片开始,还没有缓存逻辑
image.png
image.png
image.png
image.png
- operation: SDWebImageOperation
SDWebImageOperation - NSOperation的扩展协议 可cancel
image.png
image.png
operation 是一组合,缓存operation & 加载器operation
image.png
image.png
- 下载
image.png
image.png
image.png
image.png
image.png
image.png
image.png
至此,下载主干流程关键代码已然,按照惯常线性逻辑,如果下载逻辑没办法具体,线性分析链条是中断的,更别提缓存了
(三)下载核心驱动逻辑
- 搞清楚几个operation究竟是什么
operation: SDWebImageOperation协议
image.png
SDWebImageManager - loadImageWithURL:options:context:progress:completed
返回类型 operation: SDWebImageCombinedOperation(实现SDWebImageOperation协议)
SDWebImageCombinedOperation 其实是 cacheOperation:协议SDWebImageOperation 和 loaderOperation:协议SDWebImageOperation 两个协议的组合
image.png
image.png
给组合协议中的 loaderOperation 赋值
image.png
冗余 - 过渡查看operation走向
image.png
image.png
image.png
这是需要强烈吐槽一下 💢 组合协议之一
downloadOperation
与SDWebImageDownloaderOperation
为什么要用相同的名字呢,这会给读源码带来很多不必要的烦恼
image.png
image.png
SDWebImageDownloaderOperation类 与 协议SDWebImageDownloaderOperation 定义的名称一模一样, 而且 request response dataTask 定义的都一模模一个样,这样的源码,本身不是很认同
不管怎么样,最终添加进operationQueue(downloadQueue)里的operation是 downloadOperation, 最外层operation(组合协议)中的一个, 另一个是cacheOperation,
downloadOperation的实现 是个继承NSOperation的 SDWebImageDownloaderOperation类实例
downloadOperation实现 --- 继承自NSOperation的 start cancel,接收 NSURLSessionDataDelegate NSURLSessionTaskDelegate 的回调
- 几个operation流程图

- NSURLSessionTaskDelegate回调
image.png






-
下载数据完成,complete回调
image.png
到此,SDWebImage下载主要流程算是完成,接下来缓存的故事,参考(二),尽快更新