SDWebImage 源码阅读(二)

93 阅读1分钟

一、上一篇讲到进入loadImageWithURL方法,由此进入SDWebImageManager文件

1.对传入的url进行判断和类型转换

截屏2022-05-24 下午2.56.50.png

2.SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];

查找SDWebImageCombinedOperation类发现它有三个属性:

(1)一个用于缓存操作 @property (strong, nonatomic, nullable, readonly) id<SDWebImageOperation> cacheOperation;

(2)一个用于下载操作 @property (strong, nonatomic, nullable, readonly) id<SDWebImageOperation> loaderOperation;

接着继续查找SDWebImageOperation,发现它实际上是一个对NSOperation进行扩展的类

(3)@property (weak, nonatomic, nullable) SDWebImageManager *manager;

3.[self.runningOperations addObject:operation]; runningOperations用于保存所有的operation,主要用来监测是否有operation在执行,即判断running 状态。

4.进入缓存查找流程:

[self callCacheProcessForOperation:operation url:url options:result.options context:result.context progress:progressBlock completed:completedBlock];

(1)检查是否设置了不从缓存中获取

BOOL shouldQueryCache = !SD_OPTIONS_CONTAINS(options, SDWebImageFromLoaderOnly);

(2)如果需要先从缓存中获取,则调用:

截屏2022-05-24 下午4.15.29.png 由该方法进入SDImageCache文件

(3)在SDImageCache文件中:

截屏2022-05-24 下午4.17.30.png 将 SDWebImageOptions 转换为 SDImageCacheOptions,然后调用 queryCacheOperationForKey: 进行内存查找和硬盘查找

(4)在queryCacheOperationForKey:中调用completedBlock,进行下载

截屏2022-05-24 下午5.32.05.png

5.进入下载方法:

截屏2022-05-25 上午11.07.59.png

(1)BOOL shouldDownload = !SD_OPTIONS_CONTAINS(options, SDWebImageFromCacheOnly);  shouldDownload &= (!cachedImage || options & SDWebImageRefreshCached);  shouldDownload &= (![self.delegate respondsToSelector: @selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url]);

如果(没有设置只从缓存读取)& ((没有获取到缓存图片)||(即使有缓存图片也需要刷新缓存图片) ||(代理没有响应imageManager:shouldDownloadImageForURL:消息)||(imageManager:shouldDownloadImageForURL:返回yes)),则需要下载图片

(2)if ([imageLoader respondsToSelector: @selector(canRequestImageForURL:options:context:)]) {      shouldDownload &= [imageLoader canRequestImageForURL:url options:options context:context];     } else {         shouldDownload &= [imageLoader canRequestImageForURL:url];     }

通过通过 imageLoader 控制能否支持下载任务

(3) 截屏2022-05-25 下午5.47.36.png

如果 shouldDownload 为 YES,在新建任务前,如有取到 cacheImage 且 SDWebImageRefreshCached 为 YES,会将其存入 imageContext (没有则创建 imageContext)。开始新建下载任务并将其保存在 combineOperation 的 loaderOperation。

(5)由该方法进入到SDWebImageDownloader文件