前言
平时项目中经常使用到的框架中必有SDWebImage框架,这是一个很成熟图片缓存框架,而且使用非常的方便,只需一行代码就可以实现设置占位图以及在网络图片拉取成功后替换占位图的功能。虽然,乍一看只是现实了拉取网络图片的小小功能,但是,里面还包含了很多逻辑代码,也是很复杂的,你有没有深究它的实现原理呢?
实现
原理
- 在网络获取图片前,取消并移除当前对象的图片下载线程。
- 动态关联该图片url(用于图片存缓存的key),一般默认选项有占位图则先显示占位图(其中有个options选项可以不显示或者延时显示占位图等等,稍后再讲)。
- 使用关联的key作为路径,在内存中寻找该图片,找不到,再到本地中找,还是找不到,则通过url去服务器中下载。
- 在上一步中,如果在内存中找到了该图片,则直接返回;如果在本地找到了该图片,则先加载到内存中,再返回;如果需要到服务器拉取,则先把拉取到的图片加载到内存中,再存到本地,最后才返回。
- 设置对象的图片并显示。
具体逻辑如下图:
详解
1 2 3 4 5 6 7 8 9 10 11
| //通过key(一般都是url)获取下载线程 - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key { // Cancel in progress downloader from queue NSMutableDictionary *operationDictionary = [self operationDictionary]; //获取下载队列字典 id operations = [operationDictionary objectForKey:key]; //取出当前key的所有队列 ··· [operation cancel]; //取消当前线程 ··· [operationDictionary removeObjectForKey:key]; //所有队列执行完cancel操作后,在所在数组移除 } }
|
1
| objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
1 2 3 4 5
| if (!(options & SDWebImageDelayPlaceholder)) { dispatch_main_async_safe(^{ self.image = placeholder; }); }
|
- 下载图片(在缓存或者本地缓存获取也算在这里面,这里只列出了核心代码,完整代码在Github上下载SDWebImage库了解)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| //下载图片,返回一个实现SDWebImageOperation协议的对象。注:该协议只有一个cancel函数 id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { dispatch_main_sync_safe(^{ completedBlock(image, error, cacheType, url); } }); }];
//图片下载 - (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionWithFinishedBlock)completedBlock { ... //获取图片 operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) {...}]; return operation; }
//queryDiskCacheForkey函数里面首先会先去内存中寻找图片,没有再去本地找,最后才去服务器下载 - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock { //获取内存中的图片 UIImage *image = [self imageFromMemoryCacheForKey:key]; ... //获取本地储存的图片 UIImage *diskImage = [self diskImageForKey:key]; ... return operation; }
|
options作用
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { SDWebImageRetryFailed = 1 << 0, SDWebImageLowPriority = 1 << 1, SDWebImageCacheMemoryOnly = 1 << 2, SDWebImageProgressiveDownload = 1 << 3, SDWebImageRefreshCached = 1 << 4, SDWebImageContinueInBackground = 1 << 5, SDWebImageHandleCookies = 1 << 6, SDWebImageAllowInvalidSSLCertificates = 1 << 7, SDWebImageHighPriority = 1 << 8, SDWebImageDelayPlaceholder = 1 << 9, SDWebImageTransformAnimatedImage = 1 << 10, SDWebImageAvoidAutoSetImage = 1 << 11 };
|
就说说SDWebImageRetryFailed有什么作用,先看一下注释:
By default, when a URL fail to be downloaded, the URL is blacklisted so the library won’t keep trying.This flag disable this blacklisting.
默认options=0,也就是如果不传SDWebImageRetryFailed,图片下载失败了就会被加入黑名单,不会再重新下载,除非设置options=SDWebImageRetryFailed。
1 2 3 4 5 6 7 8 9 10 11
| if ( error.code != NSURLErrorNotConnectedToInternet && error.code != NSURLErrorCancelled && error.code != NSURLErrorTimedOut && error.code != NSURLErrorInternationalRoamingOff && error.code != NSURLErrorDataNotAllowed && error.code != NSURLErrorCannotFindHost && error.code != NSURLErrorCannotConnectToHost) { @synchronized (self.failedURLs) { [self.failedURLs addObject:url]; } }
|
其他
- AutoPurgeCache
NSCache子类,初始化的时候注册通知,监听内存报警,会在接收到通知后清除内存,代码如下:
1
| [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
|
- 设置image
在获取图片后没有立即刷新,而是设置刷新标志,下一次runloop的时候刷新,代码如下:
1 2
| wself.image = image; [wself setNeedsLayout];
|
总结
其实SDWebImage的源码很好理解,核心逻辑代码条理清晰,只不过,作者在这基础上完善了很多功能逻辑,功能模块分离,降低耦合度,除了UIImageView控件,还有UIButton控件也能用来设置Image。源码不多,建议感兴趣的都可以去看一下,了解一下。最后,来说一下缓存和本地缓存的区别:
- 本地缓存顾名思义是存在本地的,具体是存在应用沙盒的cache文件里,而cache里面会在某些情况下被系统自动清除,比如,内存报警,所以一般放不太重要的,不需要备份的文件。s
- 缓存是一个大概念,本地缓存也算缓存,这里NSCahce指的应该是内存,看是否已经加在到内存里了,如果已经存在内存,就可以直接从内存中获取设置图片了。