IOS 最重量级三方库 Three20 Network 缓存机制小析:

前置知

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

 

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

TTURLRequestCachePolicyDefault

= (TTURLRequestCachePolicyMemory | TTURLRequestCachePolicyDisk

| TTURLRequestCachePolicyNetwork),

TTURLRequestCachePolicyNetwork 代表使用 Last-Modified 策略,

TTURLRequestCachePolicyMemory | TTURLRequestCachePolicyDisk 代表使用内存和文件缓存资源资源ID,

 

变缓存方案:

TTURLRequest request;

//blah,blah

request.cachePolicy = cachePolicy | TTURLRequestCachePolicyEtag;

 

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

 

如何使用缓存

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

- (void)reload {

if (nil == _request && nil != _urlPath) {

UIImage* image = [[TTURLCache sharedCache] imageForURL:_urlPath];

 

if (nil != image) {

self.image = image;

 

} else {

TTURLRequest* request = [TTURLRequest requestWithURL:_urlPath delegate:self];

request.response = [[[TTURLImageResponse alloc] init] autorelease];

 

if (![request send]) {

// Put the default image in place while waiting for the request to load

if (_defaultImage && nil == self.image) {

  self.image = _defaultImage;

}

}

}

}

}

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

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

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

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

 

详细的可以看TTURLCache

 

总结:

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

posted @ 2011-05-20 17:32  hjtc  Views(1132)  Comments(0Edit  收藏  举报