SDWebImage源码解析
2020-12-10 本文已影响0人
铁头娃_e245
作为iOS端最常用的三方库之一,该库提供了具有缓存支持的异步图像下载器。
特征
- 提供了UIImageView,UIButton,MKAnnotationView的分类,用来显示网络图片,以及图片的缓存管理
- 采用异步方式来下载图片
- 采用异步方式使用memory+disk来缓存网络图片,自动管理缓存
- 逐步加载图像(支持GIF和webP格式)
- 同一个URL不会重复下载
- 自动识别无效URL,不会反复重试
- 使用GCD和ARC,不会阻塞主线程
- 当前提供Objective-C和Swift支持
结构图
高层图
它的框架如下图所示,首先通过ImageView
去通知View的Category
,之后连接到Image Manager
这个核心类,核心类分别管控着Image Cache
和Image Loader
类,他们的底层实现基于Utils&Categories
,Image Coder
和Image Transformer
。

顶层API图
顶层API类图如下图,可以看到众多UIKit分类指向UIView(WebCache)
类,之后指向Image Manager
,这里可以看到整个API的逻辑处理非常清晰,最后都会调用到Image Manager
类,后面的操作在由核心类分给其他类执行。

总体类图
总体类图如下图,这里就不详细分析了,直接看后面源码解析

基础用法
sd_setImageWithURL:
#import "UIImageView+WebCache.h" //引用
//直接加载网络图片
[imageView sd_setImageWithURL:[NSURL URLWithString:@"url"]];
sd_setImageWithURL: placeholderImage:
//先展示默认图片,当网络图片加载完成后替换
[imageView sd_setImageWithURL:[NSURL URLWithString:@"url"] placeholderImage:[UIImage imageNamed:@"defaultImage"]];
sd_setImageWithURL: placeholderImage: options:
//先展示默认图片,并设置网络图片处理方式
[imageView sd_setImageWithURL:[NSURL URLWithString:@"url"] placeholderImage:[UIImage imageNamed:@"defaultImage"] options:SDWebImageCacheMemoryOnly];
sd_setImageWithURL: placeholderImage: options: completed:
//展示默认图片,设置图片处理方式,以及执行图片加载完成后的block内部代码
[imageView sd_setImageWithURL:[NSURL URLWithString:@"url"] placeholderImage:[UIImage imageNamed:@"defaultImage"] options:SDWebImageRefreshCached completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
NSLog(@"imageSize--height:%f,width:%f",image.size.height,image.size.width);
}];
其他还有多种不同功能api可以根据场景选用,这些API的区别就在于一些可选项
placeholder
: 预览图
options
: 选项,具体每个选项的详解可以看这里
completedBlock
: 加载完成block回调

源码分析
阅读版本为5.10.0
首先,SDWebImage封装了系统类的Category(类别)为UIImageView+WebCache
,NSButton+WebCache
等等,让API使用起来更方便易用,如下图

所有的封装函数都会跳转到该类内部的
sd_setImageWithURL: placeholderImage: options: progress: completed:
中,之后经过多层跳转会进入UIView+WebCache
类的sd_internalSetImageWithURL
方法里,