您的位置:首页 > 移动开发 > IOS开发

IOS开发Three20 Network缓存机制

2013-01-05 10:46 288 查看
转自http://mobile.51cto.com/iphone-284126.htm

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

前置知识:

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, 如果包含图片,也实现的很理想。

小结:IOS开发中第三方库Three20 Network缓存机制的内容介绍完了,希望通过本文的学习能对你有所帮助!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: