NSURLCache和NSCache简介

一.单从拼写上来讲,两个东西很类似。事实是,这两个缓存没有任何联系。

二.NSURLCache提供的是URL Request缓存,可以在Memory和Disk上;NSCache提供了HTTP Request外的东西的缓存方式,在Memory上NSCache和NSDictionary类似,不同的是系统回收内存的时候它会自动删掉它的内容。AFNetworking的图片缓存采用的就是NSCache。

三.NSURLCache使用方式:

1.创建

NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil]; 

[NSURLCache setSharedURLCache:URLCache];

2.缓存的几种方式

Constant Meaning
UseProtocolCachePolicyDefault behavior
ReloadIgnoringLocalCacheDataDon't use the cache
ReloadIgnoringLocalAndRemoteCacheDataSeriously, don't use the cache
ReturnCacheDataElseLoadUse the cache (no matter how out of date), or if no cached response exists, load from the network
ReturnCacheDataDontLoadOffline mode: use the cache (no matter how out of date), but don't load from the network
ReloadRevalidatingCacheDataValidate cache against server before using

图中画横线的缓存方式其实Apple还没用实现

3.缓存实际在NSCachedURLResponse这个类中。

- (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];
}

四.NSCache使用

NSCache *myCache = ...;
NSAssert(myCache != nil, @"cache object is missing");
Widget *myWidget = [myCache objectForKey: @"Important Widget"];
if (!myWidget) {
myWidget = [[[Widget alloc] initExpensively] autorelease];
[myCache setObject: myWidget forKey: @"Important Widget"];
}
if (myWidget) {
[myWidget runOrWhatever];
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值