SDWebImage提供了以下三个category来进行缓存。web
- MKAnnotationView(WebCache)
- UIButton(WebCache)
- UIImageView(WebCache)
以最为经常使用的UIImageView为例:缓存
- UIImageView+WebCache:
setImageWithURL:placeholderImage:options:
先显示 placeholderImage ,同时由SDWebImageManager 根据 URL 来在本地查找图片。 - SDWebImageManager:
downloadWithURL:delegate:options:userInfo:
SDWebImageManager是将UIImageView+WebCache同SDImageCache连接起来的类, SDImageCache:queryDiskCacheForKey:delegate:userInfo:
用来从缓存根据CacheKey查找图片是否已经在缓存中 - 若是内存中已经有图片缓存, SDWebImageManager会回调SDImageCacheDelegate :
imageCache:didFindImage:forKey:userInfo:
- 而 UIImageView+WebCache 则回调SDWebImageManagerDelegate:
webImageManager:didFinishWithImage:
来显示图片。 - 若是内存中没有图片缓存,那么生成 NSInvocationOperation 添加到队列,从硬盘查找图片是否已被下载缓存。
- 根据 URLKey 在硬盘缓存目录下尝试读取图片文件。这一步是在 NSOperation 进行的操做,因此回主线程进行结果回调
notifyDelegate:
。 - 若是上一操做从硬盘读取到了图片,将图片添加到内存缓存中(若是空闲内存太小,会先清空内存缓存)。SDImageCacheDelegate 回调
imageCache:didFindImage:forKey:userInfo:
。进而回调展现图片。 - 若是从硬盘缓存目录读取不到图片,说明全部缓存都不存在该图片,须要下载图片,回调
imageCache:didNotFindImageForKey:userInfo:
。 - 共享或从新生成一个下载器
SDWebImageDownloader
开始下载图片。 - 图片下载由 NSURLConnection 来作,实现相关 delegate 来判断图片下载中、下载完成和下载失败。
connection:didReceiveData:
中利用 ImageIO 作了按图片下载进度加载效果。connectionDidFinishLoading:
数据下载完成后交给SDWebImageDecoder
作图片解码处理。- 图片解码处理在一个 NSOperationQueue 完成,不会拖慢主线程 UI。若是有须要对下载的图片进行二次处理,最好也在这里完成,效率会好不少。
- 在主线程
notifyDelegateOnMainThreadWithInfo:
宣告解码完成,imageDecoder:didFinishDecodingImage:userInfo:
回调给 SDWebImageDownloader。 imageDownloader:didFinishWithImage:
回调给 SDWebImageManager 告知图片下载完成。- 通知全部的 downloadDelegates 下载完成,回调给须要的地方展现图片。
- 将图片保存到 SDImageCache 中,内存缓存和硬盘缓存同时保存。
- 写文件到硬盘在单独 NSInvocationOperation 中完成,避免拖慢主线程。
- 若是是在iOS上运行,SDImageCache 在初始化的时候会注册notification 到 UIApplicationDidReceiveMemoryWarningNotification 以及 UIApplicationWillTerminateNotification,在内存警告的时候清理内存图片缓存,应用结束的时候清理过时图片。
SDWebImagePrefetcher
能够预先下载图片,方便后续使用。
转自 http://www.overcode.hk/?p=449