SDWebImage和AFNetworking的缓存机制

一、SDWebImage缓存图片的机制

SDWebImage是一个很厉害的图片缓存的框架。既ASIHttp+AsyncImage之后,我一直使用AFNetworking集成的UIImageView+AFNetworking.h,但后者对于图片的缓存实际应用的是NSURLCache自带的cache机制。而NSURLCache每次都要把缓存的raw  data 再转化为UIImage,就带来了数据处理和内存方面的更多操作。具体的比较在这里

SDWebImage提供了如下三个category来进行缓存。

以最为常用的UIImageView为例:

  1. UIImageView+WebCache:  setImageWithURL:placeholderImage:options: 先显示 placeholderImage ,同时由SDWebImageManager 根据 URL 来在本地查找图片。
  2. SDWebImageManager: downloadWithURL:delegate:options:userInfo: SDWebImageManager是将UIImageView+WebCache同SDImageCache链接起来的类, SDImageCache: queryDiskCacheForKey:delegate:userInfo:用来从缓存根据CacheKey查找图片是否已经在缓存中
  3. 如果内存中已经有图片缓存, SDWebImageManager会回调SDImageCacheDelegate : imageCache:didFindImage:forKey:userInfo:
  4. 而 UIImageView+WebCache 则回调SDWebImageManagerDelegate:  webImageManager:didFinishWithImage:来显示图片。
  5. 如果内存中没有图片缓存,那么生成 NSInvocationOperation 添加到队列,从硬盘查找图片是否已被下载缓存。
  6. 根据 URLKey 在硬盘缓存目录下尝试读取图片文件。这一步是在 NSOperation 进行的操作,所以回主线程进行结果回调 notifyDelegate:
  7. 如果上一操作从硬盘读取到了图片,将图片添加到内存缓存中(如果空闲内存过小,会先清空内存缓存)。SDImageCacheDelegate 回调 imageCache:didFindImage:forKey:userInfo:。进而回调展示图片。
  8. 如果从硬盘缓存目录读取不到图片,说明所有缓存都不存在该图片,需要下载图片,回调 imageCache:didNotFindImageForKey:userInfo:
  9. 共享或重新生成一个下载器 SDWebImageDownloader 开始下载图片。
  10. 图片下载由 NSURLConnection 来做,实现相关 delegate 来判断图片下载中、下载完成和下载失败。
  11. connection:didReceiveData: 中利用 ImageIO 做了按图片下载进度加载效果。
  12. connectionDidFinishLoading: 数据下载完成后交给 SDWebImageDecoder 做图片解码处理。
  13. 图片解码处理在一个 NSOperationQueue 完成,不会拖慢主线程 UI。如果有需要对下载的图片进行二次处理,最好也在这里完成,效率会好很多。
  14. 在主线程 notifyDelegateOnMainThreadWithInfo: 宣告解码完成,imageDecoder:didFinishDecodingImage:userInfo: 回调给 SDWebImageDownloader。
  15. imageDownloader:didFinishWithImage: 回调给 SDWebImageManager 告知图片下载完成。
  16. 通知所有的 downloadDelegates 下载完成,回调给需要的地方展示图片。
  17. 将图片保存到 SDImageCache 中,内存缓存和硬盘缓存同时保存。
  18. 写文件到硬盘在单独 NSInvocationOperation 中完成,避免拖慢主线程。
  19.  如果是在iOS上运行,SDImageCache 在初始化的时候会注册notification 到 UIApplicationDidReceiveMemoryWarningNotification 以及  UIApplicationWillTerminateNotification,在内存警告的时候清理内存图片缓存,应用结束的时候清理过期图片。

  1. SDWebImagePrefetcher 可以预先下载图片,方便后续使用。

二、(译)缓存在AFNetworking中是如何工作的?AFImageCache和NSUrlCache给你答案

如果你是一名使用Mattt Thompson网络框架AFNetworking的iOS开发者(如果你不是,那还等什么呢?),也许你对这个框架中的缓存机制很好奇或者疑惑,并想学习如何在自己的app中充分利用这种机制。

AFNetworking实际上使用了两个独立的缓存机制:

    ● AFImagecache:一个提供图片内存缓存的类,继承自NSCache。

    ● NSURLCache:NSURLConnection's默认的URL缓存机制,用于存储NSURLResponse对象:一个默认缓存在内存,通过配置可以缓存到磁盘的类。

为了理解每个缓存系统是如何工作的,我们看一下他们是如何定义的。

AFImageCache是如何工作的

AFImageCache是UIImageView+AFNetworking分类的一部分。它继承自NSCache,通过一个URL字符串作为它的key(从NSURLRequest中获取)来存储UIImage对象。

AFImageCache定义:

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@interface AFImageCache : NSCache <AFImageCache>
 
// singleton instantiation :
 
+ (id <AFImageCache>)sharedImageCache {    
     static  AFImageCache *_af_defaultImageCache = nil;    
     static  dispatch_once_t oncePredicate;    
     dispatch_once(&oncePredicate, ^{
         _af_defaultImageCache = [[AFImageCache alloc] init];
         
         // clears out cache on memory warning :
 
         [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * __unused notification) {
             [_af_defaultImageCache removeAllObjects];
         }];
     });
 
     // key from [[NSURLRequest URL] absoluteString] :
     
     static  inline  NSString * AFImageCacheKeyFromURLRequest(NSURLRequest *request) {    
         return  [[request URL] absoluteString];
}
 
@implementation AFImageCache
 
// write to cache if proper policy on NSURLRequest :
 
- (UIImage *)cachedImageForRequest:(NSURLRequest *)request {    
     switch  ([request cachePolicy]) {        
         case  NSURLRequestReloadIgnoringCacheData:        
         case  NSURLRequestReloadIgnoringLocalAndRemoteCacheData:            
             return  nil;        
         default :            
             break ;
     }    
     
     return  [self objectForKey:AFImageCacheKeyFromURLRequest(request)];
}
 
// read from cache :
 
- ( void )cacheImage:(UIImage *)image forRequest:(NSURLRequest *)request {    
     if  (image && request) {
         [self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)];
     }
}


AFImageCache 从 AFNetworking 2.1开始可以进行配置了。有一个公共方法setSharedImageCache。详细文档可以看这里 。它把所有可访问的UIImage对象存到了NSCache。当UIImage对象释放之后NSCache会进行处理。如果你想观察images什么时候释放,可以实现NSCacheDelegate的cache:willEvictObject方法

NSURLCache如何工作

默认是可以的,但最好还是手动配置一下

既然AFNetworking使用NSURLConnection,它利用了原生的缓存机制NSURLCache。NSURLCache缓存了从服务器返回的NSURLResponse对象。

NSURLCache的shareCache方法默认是可以使用的,缓存获取的内容。不幸的是,它的默认配置只是缓存在内存并没有写到硬盘。为了解决这个问题,你可以声明一个 sharedCache,像这样:

1
2
3
4
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:2 * 1024 * 1024
                                               diskCapacity:100 * 1024 * 1024
                                               diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];

这样,我们声明了一个2M内存,100M磁盘空间的NSURLCache。

对NSURLRequest对象设置缓存策略

NSURLCache对每个NSURLRequest对象都会遵守缓存策略(NSURLRequestCachePolicy)。策略定义如下:

    ● NSURLRequestUseProtocolCachePolicy:指定定义在协议实现里的缓存逻辑被用于URL请求。这是URL请求的默认策略

    ● NSURLRequestReloadIgnoringLocalCacheData:忽略本地缓存,从源加载

    ● NSURLRequestReloadIgnoringLocalAndRemoteCacheData:忽略本地&服务器缓存,从源加载

    ● NSURLRequestReturnCacheDataElseLoad:先从缓存加载,如果没有缓存,从源加载

    ● NSURLRequestReturnCacheDataDontLoad离线模式,加载缓存数据(无论是否过期),不从源加载

    ● NSURLRequestReloadRevalidatingCacheData存在的缓存数据先确认有效性,无效的话从源加载

用NSURLCache缓存到磁盘

Cache-Control HTTP Header

Cache-Control或者Expires header 必须在从服务器返回的 HTTP response header 中,用于客户端的缓存(Cache-Control header 优先权高于 Expires header)。这里边有很多需要注意的地方,Cache Control可以有被定义为 max-age的参数(在更新响应之前缓存多长时间),public/private 访问,或者 no-cache(不缓存响应数据),这里有一个关于HTTP cache headers的文章。

Subclass NSURLCache for Ultimate Control

如果你想绕过 Cache-Control 需求,定义你自己的规则来读写一个带有 NSURLResponse对象的NSURLCache,你可以继承 NSURLCache。

这里有个例子,使用 CACHE_EXPIRES 来判断在获取源数据之前对缓存数据保留多长时间。

(感谢 Mattt Thompson反馈)

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@interface CustomURLCache : NSURLCache
 
static  NSString *  const  CustomURLCacheExpirationKey = @ "CustomURLCacheExpiration" ;
static  NSTimeInterval  const  CustomURLCacheExpirationInterval = 600;
 
@implementation CustomURLCache
 
+ (instancetype)standardURLCache {
     static  CustomURLCache *_standardURLCache = nil;
     static  dispatch_once_t onceToken;
     dispatch_once(&onceToken, ^{
         _standardURLCache = [[CustomURLCache alloc]
                                  initWithMemoryCapacity:(2 * 1024 * 1024)
                                  diskCapacity:(100 * 1024 * 1024)
                                  diskPath:nil];
     }
 
     return  _standardURLCache;
}
 
#pragma mark - NSURLCache
 
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
     NSCachedURLResponse *cachedResponse = [super cachedResponseForRequest:request];
 
     if  (cachedResponse) {
         NSDate* cacheDate = cachedResponse.userInfo[CustomURLCacheExpirationKey];
         NSDate* cacheExpirationDate = [cacheDate dateByAddingTimeInterval:CustomURLCacheExpirationInterval];
         if  ([cacheExpirationDate compare:[NSDate date]] == NSOrderedAscending) {
             [self removeCachedResponseForRequest:request];
             return  nil;
         }
     }
}
 
     return  cachedResponse;
}
 
- ( void )storeCachedResponse:(NSCachedURLResponse *)cachedResponse
                  forRequest:(NSURLRequest *)request
{
     NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:cachedResponse.userInfo];
     userInfo[CustomURLCacheExpirationKey] = [NSDate date];
 
     NSCachedURLResponse *modifiedCachedResponse = [[NSCachedURLResponse alloc] initWithResponse:cachedResponse.response data:cachedResponse.data userInfo:userInfo storagePolicy:cachedResponse.storagePolicy];
 
     [super storeCachedResponse:modifiedCachedResponse forRequest:request];
}
 
@end

既然你有了自己的 NSURLCache子类,不要忘了在AppDelegate里边初始化并使用它

1
2
3
4
CustomURLCache *URLCache = [[CustomURLCache alloc] initWithMemoryCapacity:2 * 1024 * 1024
                                                    diskCapacity:100 * 1024 * 1024
                                                                  diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];

Overriding the NSURLResponse before caching

-connection:willCacheResponse代理方法是在被缓存之前用于截断和编辑由NSURLConnection创建的NSURLCacheResponse的地方。为了编辑NSURLCacheResponse,返回一个可变的拷贝,如下(代码来自NSHipster blog):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                   willCacheResponse:(NSCachedURLResponse *)cachedResponse {
     NSMutableDictionary *mutableUserInfo = [[cachedResponse userInfo] mutableCopy];
     NSMutableData *mutableData = [[cachedResponse data] mutableCopy];
     NSURLCacheStoragePolicy storagePolicy = NSURLCacheStorageAllowedInMemoryOnly;
 
     // ...
 
     return  [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response]
                                                     data:mutableData
                                                 userInfo:mutableUserInfo
                                            storagePolicy:storagePolicy];
}
 
// If you do not wish to cache the NSURLCachedResponse, just return nil from the delegate function:
 
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                   willCacheResponse:(NSCachedURLResponse *)cachedResponse {
     return  nil;
}

Disabling NSURLCache

不想使用 NSURLCache,可以,只需要将内存和磁盘空间容量设为零就可以了

1
2
3
4
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0
                                               diskCapacity:0
                                               diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];

总结

我写这篇博客是为了iOS社区贡献一份力,总结了一下我在处理关于 AFNetworking缓存相关的问题。我们有个内部App加载了好多图片,导致内存问题以及性能问题。我主要职责就是诊断这个App的缓存行为。在这个研究过程中,我在网上搜索了好多资料并且做了好多调试。然后我总结之后写到了这篇博客中。我希望这篇文章能够为其他人用AFNetworking的时候提供帮助,真心希望对你们有用处!

外文地址:http://blog.originate.com/blog/2014/02/20/afimagecache-vs-nsurlcache/

来源:tian's blog

原文地址:http://devtian.me/2015/03/24/%E8%AF%91-%E7%BC%93%E5%AD%98%E5%9C%A8AFNetworking%E4%B8%AD%E6%98%AF%E5%A6%82%E4%BD%95%E5%B7%A5%E4%BD%9C%E7%9A%84/ 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值