使用缓存的目的是为了使用的应用程序能更快速的响应用户输入,是程序高效的运行。有时候我们需要将远程web服务器获取的数据缓存起来,减少对同一个url多次请求。

内存缓存我们可以使用sdk中的NSURLCache类。NSURLRequest需要一个缓存参数来说明它请求的url何如缓存数据的,我们先看下它的CachePolicy类型。


NSURLRequest *request = [NSURLRequest requestWithURL:url  

 
//NSURLRequest初始化方法第一个参数:请求访问路径,第二个参数:缓存协议,第三个参数:网络请求超时时间(秒)
 
其中缓存协议是个枚举类型包含:
 
NSURLRequestUseProtocolCachePolicy(基础策略)
 
NSURLRequestReloadIgnoringLocalCacheData(忽略缓存直接从原始地址下载)
 
NSURLRequestReturnCacheDataElseLoad(首先使用缓存,如果没有本地缓存,才从原地址下载)
 
NSURLRequestReturnCacheDataDontLoad(使用本地缓存,从不下载,如果本地没有缓存,则请求失败,此策略多用于离线操作)
 
NSURLRequestReloadIgnoringLocalAndRemoteCacheData(无视任何缓存策略,无论是本地的还是远程的,总是从原地址重新下载)
 
NSURLRequestReloadRevalidatingCacheData(验证本地数据与远程数据是否相同,如果不同则下载远程数据,否则使用本地数据)



1、NSURLRequestUseProtocolCachePolicy NSURLRequest默认的cache policy,使用Protocol协议定义。
2、NSURLRequestReloadIgnoringCacheData 忽略缓存直接从原始地址下载。
3、NSURLRequestReturnCacheDataElseLoad 只有在cache中不存在data时才从原始地址下载。
4、NSURLRequestReturnCacheDataDontLoad 只使用cache数据,如果不存在cache,请求失败;用于没有建立网络连接离线模式;
5、NSURLRequestReloadIgnoringLocalAndRemoteCacheData:忽略本地和远程的缓存数据,直接从原始地址下载,与NSURLRequestReloadIgnoringCacheData类似。
6NSURLRequestReloadRevalidatingCacheData:验证本地数据与远程数据是否相同,如果不同则下载远程数据,否则使用本地数据。

NSURLCache还提供了很多方法,来方便我们实现应用程序的缓存机制。下面我通过一个例子来说明,这个例子减少我们对同一个url多次请求。看下面代码:


-(void) buttonPress:(id) sender


          {         


NSString *paramURLAsString= @"http://www.baidu.com/";


if ([paramURLAsString length] == 0){


NSLog(@"Nil or empty URL is given");


return;


}


NSURLCache *urlCache = [NSURLCache sharedURLCache];


/* 设置缓存的大小为1M*/


[urlCache setMemoryCapacity:1*1024*1024];


//创建一个nsurl


NSURL *url = [NSURL URLWithString:paramURLAsString];


//创建一个请求


NSMutableURLRequest *request =


[NSMutableURLRequest


requestWithURL:url


cachePolicy:NSURLRequestUseProtocolCachePolicy


timeoutInterval:60.0f];


//从请求中获取缓存输出


NSCachedURLResponse *response =


[urlCache cachedResponseForRequest:request];


//判断是否有缓存


if (response != nil){


NSLog(@"如果有缓存输出,从缓存中获取数据");


[request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];


}


self.connection = nil;


/* 创建NSURLConnection*/


NSURLConnection *newConnection =


[[NSURLConnection alloc] initWithRequest:request


delegate:self


startImmediately:YES];


self.connection = newConnection;


[newConnection release];


          }



这个例子中,我们请求url为www.baidu.com的网站。如果这个url被缓存了,我们直接从缓存中获取数据,否则从www.baidu.com站点上重新获取数据。我们设置了缓存大小为1M。

使用下面代码,我将请求的过程打印出来:


- (void)  connection:(NSURLConnection *)connection


didReceiveResponse:(NSURLResponse *)response{


NSLog(@"将接收输出");


          }         


- (NSURLRequest *)connection:(NSURLConnection *)connection


willSendRequest:(NSURLRequest *)request


redirectResponse:(NSURLResponse *)redirectResponse{


NSLog(@"即将发送请求");


return(request);


          }         


- (void)connection:(NSURLConnection *)connection


didReceiveData:(NSData *)data{


NSLog(@"接受数据");


NSLog(@"数据长度为 = %lu", (unsigned long)[data length]);


          }         


- (NSCachedURLResponse *)connection:(NSURLConnection *)connection


willCacheResponse:(NSCachedURLResponse *)cachedResponse{


NSLog(@"将缓存输出");


return(cachedResponse);


          }         


- (void)connectionDidFinishLoading:(NSURLConnection *)connection{


NSLog(@"请求完成");


          }         


- (void)connection:(NSURLConnection *)connection


didFailWithError:(NSError *)error{


NSLog(@"请求失败");


          }


当我们第一次点击界面上的按钮,打印的结果如下:


18:50:24.910 Caching[3971:207] 即将发送请求         


          18:50:28.557 Caching[3971:207] 将接收输出         


          18:50:31.677 Caching[3971:207] 接受数据         


          18:50:31.681 Caching[3971:207] 数据长度为 = 4414         


          18:50:31.682 Caching[3971:207] 接受数据         


          18:50:31.682 Caching[3971:207] 数据长度为 = 2996         


          18:50:38.107 Caching[3971:207] 将缓存输出         


          18:50:38.109 Caching[3971:207] 请求完成


在看我们第二次点击界面上的按钮,打印结果如下:


18:52:18.894 Caching[3971:207] 即将发送请求         


          18:52:18.895 Caching[3971:207] 将接收输出         


          18:52:18.895 Caching[3971:207] 接受数据         


          18:52:18.896 Caching[3971:207] 数据长度为 = 7410         


          18:52:18.896 Caching[3971:207] 请求完成



我们看到没有“将缓存输出”一项,请求到的数据是第一次请求的累积,也就是第二次是从内存中获取数据的。


NSURLCache:

NSURLCache *cache = [NSURLCache sharedURLCache];

NSURLCache 仅支持内存缓存,不支持硬盘缓存。

    1. - (void) downloadURL:(NSString *)paramURLAsString{  
    2.   
    3. if
    4. "Nil or empty URL is given");  
    5. return;  
    6. }  
    7.   
    8. /* Get the shared URL Cache object. No need to create a new one */
    9. NSURLCache *urlCache = [NSURLCache sharedURLCache];  
    10.   
    11. /* We will store up to 1 Megabyte of data into the cache */
    12. [urlCache setMemoryCapacity:1*1024*1024];  
    13.   
    14. /* For our request, we need an instance of NSURL so let's retrieve
    15. that from the string that we created before */
    16. NSURL *url = [NSURL URLWithString:paramURLAsString];  
    17.   
    18. /* And this is our request */
    19. NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0f];  
    20.   
    21. /* Try to get a cached response to our request.
    22. This might come back as nil */
    23. NSCachedURLResponse *response =[urlCache cachedResponseForRequest:request];  
    24.   
    25. /* Do we have a cached response? */
    26. if
    27. "Cached response exists. Loading data from cache...");  
    28.     [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];  
    29. }  
    30.   
    31. self.connection = nil;  
    32.   
    33. /* Start the connection with the request */
    34. NSURLConnection *newConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];  
    35. self.connection = newConnection;  
    36. [newConnection release];  
    37.   
    38. }