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

转载地址: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/

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

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

  • AFImagecache:一个提供图片内存缓存的类,继承自NSCache
  • NSURLCache:NSURLConnection's默认的URL缓存机制,用于存储NSURLResponse对象:一个默认缓存在内存,通过配置可以缓存到磁盘的类。

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

AFImageCache是如何工作的

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

AFImageCache定义:

@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什么时候释放,可以实现NSCacheDelegatecache:willEvictObject方法

NSURLCache如何工作

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

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

NSURLCacheshareCache方法默认是可以使用的,缓存获取的内容。不幸的是,它的默认配置只是缓存在内存并没有写到硬盘。为了解决这个问题,你可以声明一个 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/

posted @ 2015-03-25 07:43  OneByte  阅读(483)  评论(0编辑  收藏  举报