IOS开发Three20 Network缓存机制

转自http://mobile.51cto.com/iphone-284126.htm

IOS开发中第三方库Three20 Network缓存机制是本文要介绍的内容,主要是来学习Three20Network缓存机制,具体内容来看本文详细内容讲解。

前置知识:

http协议自带的Last-Modified和ETag,详细的网上搜索下就行了。简单来说就是,服务器在返回资源时包含一个ID(时间或是某种token),客户端缓存该ID,下一次再请求同一资源时,包含这个ID,服务器根据此ID来判断资源是否改变,从而返回不同的结果(200或是304)。

Three20实现的默认缓存方案是:

  1. TTURLRequestCachePolicyDefault 
  2. = (TTURLRequestCachePolicyMemory | TTURLRequestCachePolicyDisk  
  3. | TTURLRequestCachePolicyNetwork),  
  4. TTURLRequestCachePolicyNetwork 代表使用 Last-Modified 策略,  
  5. TTURLRequestCachePolicyMemory | TTURLRequestCachePolicyDisk 代表使用内存和文件缓存资源和资源ID, 

改变缓存方案:

  1. TTURLRequest request;  
  2. //blah,blah  
  3. request.cachePolicy = cachePolicy | TTURLRequestCachePolicyEtag; 

这里增加了Etag的功能,如果服务器支持的话,毫无疑问这是最佳的方案。其他类推,比如不需要缓存。

如何使用缓存:

这里拉一段TTImageView的代码,一看就知道:

  1. - (void)reload {  
  2. if (nil == _request && nil != _urlPath) {  
  3. UIImage* image = [[TTURLCache sharedCache] imageForURL:_urlPath];  
  4. if (nil != image) {  
  5. self.image = image;  
  6. } else {  
  7.  
  8. TTURLRequest* request = [TTURLRequest requestWithURL:_urlPath delegate:self];  
  9. request.response = [[[TTURLImageResponse alloc] init] autorelease];  
  10. if (![request send]) {  
  11. // Put the default image in place while waiting for the request to load  
  12. if (_defaultImage && nil == self.image) {  
  13. self.image = _defaultImage;  
  14. }  
  15. }  
  16. }  
  17. }  

使用TTURLCache的单例,可以获取任意URL资源的本地缓存。这里的逻辑是这样的:

首先判断内存中是否存在这种图片:

  1. UIImage* image = [[TTURLCache sharedCache] imageForURL:_urlPath] 

如果不存在,发起一个request,使用默认的policy,获取该图片。假设该图片上次打开程序时已经下载过,已经缓存在disk(这是默认的),并且图片在服务器上没有变更,且服务器支持if-modified, request默认就会返回disk上的图片。

详细的可以看TTURLCache,如果手动send 一个request,则默认的policy就可以很好的实现了缓存机制。一些内置的控件,比如TTTableView, 如果包含图片,也实现的很理想。

小结:IOS开发中第三方库Three20 Network缓存机制的内容介绍完了,希望通过本文的学习能对你有所帮助!

原文地址:https://www.cnblogs.com/jiangshiyong/p/2845361.html