iOS开发之本地缓存机制

功能需求
这个缓存机制满足下面这些功能。
1、可以将数据缓存到本地磁盘。
2、可以判断一个资源是否已经被缓存。如果已经被缓存,在请求相同的资源,先到本地磁盘搜索。
3、可以判断文件缓存什么时候过期。这里为了简单起见这里,我们在请求url资源的时候,给每次请求的文件设定一个过期的时间。
4、可以实现:如果文件已经被缓存,而且没有过期,这将本地的数据返回,否则重新请求url。
5、可以实现:如果文件下载不成功或者下载没有完成,下次打开程序的时候,移除这些没有成功或者没有下载完成的文件。
6、可以实现:同时请求或者下载多个资源。
设计实现:
1、设计一个CacheItem类,用来请求一个web连接,它的一个实例表示一个缓存项。这个CacheItem类,需要一个url创建一个NSURLConnection,去请求web资源。使用CacheItem类主要用来请求web资源。
 
 
  1. /* ---------缓存项-------------- */   
  1.  
  1. @interface CacheItem : NSObject {   
  1. @public   
  1.   id<CacheItemDelegate> delegate;   
  1.     //web地址   
  1.   NSString              *remoteURL;   
  1. @private   
  1.     //是否正在下载   
  1.   BOOL                  isDownloading;   
  1.        //NSMutableData对象   
  1.   NSMutableData         *connectionData;   
  1.    //NSURLConnection对象   
  1.   NSURLConnection       *connection;   
  1. }   
  1.  
  1. /* -------------------------- */   
  1.  
  1. @property (nonatomic, retain) id<CacheItemDelegate> delegate;   
  1. @property (nonatomic, retain) NSString  *remoteURL;   
  1. @property (nonatomic, assign) BOOL      isDownloading;   
  1. @property (nonatomic, retain) NSMutableData *connectionData;   
  1. @property (nonatomic, retain) NSURLConnection *connection;   
  1.  
  1. /* ----------开始下载方法----------- */   
  1.  
  1. - (BOOL) startDownloadingURL:(NSString *)paramRemoteURL;   
  1.  
  1. @end   
2、在NSURLConnection开始请求之前,调用CachedDownloadManager类,来搜索和管理本地的缓存文件。将缓存文件的情况保存到一个字典类中。这个字典设计如下:
  1. {   
  1.  
  1.   "http://www.cnn.com" =     {   
  1.  
  1.     DownloadEndDate = "2011-08-02 07:51:57 +0100";   
  1.  
  1.     DownloadStartDate = "2011-08-02 07:51:55 +0100";   
  1.  
  1.     ExpiresInSeconds = 20;   
  1.  
  1.     ExpiryDate = "2011-08-02 07:52:17 +0100";   
  1.  
  1.     LocalURL = "/var/mobile/Applications/ApplicationID/Documents/   
  1.  
  1.                 httpwww.cnn.com.cache";   
  1.  
  1.   };   
  1.  
  1.   "http://www.baidu.com" =     {   
  1.  
  1.     DownloadEndDate = "2011-08-02 07:51:49 +0100";   
  1.  
  1.     DownloadStartDate = "2011-08-02 07:51:44 +0100";   
  1.  
  1.     ExpiresInSeconds = 20;   
  1.  
  1.     ExpiryDate = "2011-08-02 07:52:09 +0100";   
  1.  
  1.     LocalURL = "/var/mobile/Applications/ApplicationID/Documents/   
  1.  
  1.                 httpwww.oreilly.com.cache";   
  1.  
  1.   };   
  1.  
  1. }   
上面这个字典里面嵌套了字典。里面那层字典表示一个缓存项的缓存信息:下载结束时间、下载开始时间、缓存有效时间、缓存过期时间、缓存到本地的路径。 下面看下CachedDownloadManager类。用它来实现和封装我们的缓存策略。
  1. /* -----------CachedDownloadManager-------------- */ 
  1.  
  1. @interface CachedDownloadManager : NSObject 
  1.  
  1.  
  1. @public 
  1.  
  1. id delegate; 
  1.  
  1. @private 
  1.  
  1. //记录缓存数据的字典 
  1.  
  1. NSMutableDictionary *cacheDictionary; 
  1.  
  1. //缓存的路径 
  1.  
  1. NSString *cacheDictionaryPath; 
  1.  
  1.  
  1. @property (nonatomic, assign) 
  1.  
  1. id delegate; 
  1.  
  1. @property (nonatomic, copy) 
  1.  
  1. NSMutableDictionary *cacheDictionary; 
  1.  
  1. @property (nonatomic, retain) 
  1.  
  1. NSString *cacheDictionaryPath; 
  1.  
  1. /* 保持缓存字典 */ 
  1.  
  1. - (BOOL) saveCacheDictionary; 
  1.  
  1. /* 公有方法:下载 */ 
  1.  
  1. - (BOOL) download:(NSString *)paramURLAsString 
  1.  
  1. urlMustExpireInSeconds:(NSTimeInterval)paramURLMustExpireInSeconds 
  1.  
  1. updateExpiryDateIfInCache:(BOOL)paramUpdateExpiryDateIfInCache; 
  1.  
  1. /* -------------------------- */ 
  1.  
  1. @end 
  1.  
从上面代码可以看出,这个管理缓存的类中,有一个缓存字典:cacheDictionary,用来表示所有资源的缓存情况;cacheDictionaryPath用来表示缓存的路径;saveCacheDictionary用来将缓存字典归档到本地文件中。download:urlMustExpireInSeconds:updateExpiryDateIfInCache是一个公共接口,通过传递url、缓存过期时间、是否更新缓存过期时间三个参数来方便的使用,实现我们的缓存策略。 3、如果这个文件已经被下载,而且没有过期,则从本地获取文件的数据。如果文件已经过期,则重新下载。我们通过download:urlMustExpireInSeconds:updateExpiryDateIfInCache方法来实现,主要看这个方法的代码:
  1. /* ---------下载-------------- */ 
  1.  
  1. - (BOOL) download:(NSString *)paramURLAsString 
  1.  
  1. urlMustExpireInSeconds:(NSTimeInterval)paramURLMustExpireInSeconds 
  1.  
  1. updateExpiryDateIfInCache:(BOOL)paramUpdateExpiryDateIfInCache{ 
  1.  
  1. BOOL result = NO
  1.  
  1. if (self.cacheDictionary == nil || 
  1.  
  1. [paramURLAsString length] == 0){ 
  1.  
  1. return(NO); 
  1.  
  1.  
  1. paramURLAsString = [paramURLAsString lowercaseString]; 
  1.  
  1. //根据url,从字典中获取缓存项的相关数据 
  1.  
  1. NSMutableDictionary *itemDictionary = 
  1.  
  1. [self.cacheDictionary objectForKey:paramURLAsString]; 
  1.  
  1. /* 使用下面这些变量帮助我们理解缓存逻辑 */ 
  1.  
  1. //文件是否已经被缓存 
  1.  
  1. BOOL fileHasBeenCached = NO
  1.  
  1. //缓存是否过期 
  1.  
  1. BOOL cachedFileHasExpired = NO
  1.  
  1. //缓存文件是否存在 
  1.  
  1. BOOL cachedFileExists = NO
  1.  
  1. //缓存文件能否被加载 
  1.  
  1. BOOL cachedFileDataCanBeLoaded = NO
  1.  
  1. //缓存文件数据 
  1.  
  1. NSData *cachedFileData = nil
  1.  
  1. //缓存文件是否完全下载 
  1.  
  1. BOOL cachedFileIsFullyDownloaded = NO
  1.  
  1. //缓存文件是否已经下载 
  1.  
  1. BOOL cachedFileIsBeingDownloaded = NO
  1.  
  1. //过期时间 
  1.  
  1. NSDate *expiryDate = nil
  1.  
  1. //下载结束时间 
  1.  
  1. NSDate *downloadEndDate = nil
  1.  
  1. //下载开始时间 
  1.  
  1. NSDate *downloadStartDate = nil
  1.  
  1. //本地缓存路径 
  1.  
  1. NSString *localURL = nil
  1.  
  1. //有效时间 
  1.  
  1. NSNumber *expiresInSeconds = nil
  1.  
  1. NSDate *now = [NSDate date]; 
  1.  
  1. if (itemDictionary != nil){ 
  1.  
  1. fileHasBeenCached = YES
  1.  
  1.  
  1. //如果文件已经被缓存,则从缓存项相关数据中获取相关的值 
  1.  
  1. if (fileHasBeenCached == YES){ 
  1.  
  1. expiryDate = [itemDictionary 
  1.  
  1. objectForKey:CachedKeyExpiryDate]; 
  1.  
  1. downloadEndDate = [itemDictionary 
  1.  
  1. objectForKey:CachedKeyDownloadEndDate]; 
  1.  
  1. downloadStartDate = [itemDictionary 
  1.  
  1. objectForKey:CachedKeyDownloadStartDate]; 
  1.  
  1. localURL = [itemDictionary 
  1.  
  1. objectForKey:CachedKeyLocalURL]; 
  1.  
  1. expiresInSeconds = [itemDictionary 
  1.  
  1. objectForKey:CachedKeyExpiresInSeconds]; 
  1.  
  1. //如果下载开始和结束时间不为空,表示文件全部被下载 
  1.  
  1. if (downloadEndDate != nil && 
  1.  
  1. downloadStartDate != nil){ 
  1.  
  1. cachedFileIsFullyDownloaded = YES
  1.  
  1.  
  1. /* 如果expiresInSeconds不为空,downloadEndDate为空,表示文件已经正在下载 */ 
  1.  
  1. if (expiresInSeconds != nil && 
  1.  
  1. downloadEndDate == nil){ 
  1.  
  1. cachedFileIsBeingDownloaded = YES
  1.  
  1.  
  1. /* 判断缓存是否过期 */ 
  1.  
  1. if (expiryDate != nil && 
  1.  
  1. [now timeIntervalSinceDate:expiryDate] > 0.0){ 
  1.  
  1. cachedFileHasExpired = YES
  1.  
  1.  
  1. if (cachedFileHasExpired == NO){ 
  1.  
  1. /* 如果缓存文件没有过期,加载缓存文件,并且更新过期时间 */ 
  1.  
  1. NSFileManager *fileManager = [[NSFileManager alloc] init]; 
  1.  
  1. if ([fileManager fileExistsAtPath:localURL] == YES){ 
  1.  
  1. cachedFileExists = YES
  1.  
  1. cachedFileData = [NSData dataWithContentsOfFile:localURL]; 
  1.  
  1. if (cachedFileData != nil){ 
  1.  
  1. cachedFileDataCanBeLoaded = YES
  1.  
  1. } /* if (cachedFileData != nil){ */ 
  1.  
  1. } /* if ([fileManager fileExistsAtPath:localURL] == YES){ */ 
  1.  
  1. [fileManager release]; 
  1.  
  1. /* 更新缓存时间 */ 
  1.  
  1. if (paramUpdateExpiryDateIfInCache == YES){ 
  1.  
  1. NSDate *newExpiryDate = 
  1.  
  1. [NSDate dateWithTimeIntervalSinceNow: 
  1.  
  1. paramURLMustExpireInSeconds]; 
  1.  
  1. NSLog(@"Updating the expiry date from %@ to %@.", 
  1.  
  1. expiryDate, 
  1.  
  1. newExpiryDate); 
  1.  
  1. [itemDictionary setObject:newExpiryDate 
  1.  
  1. forKey:CachedKeyExpiryDate]; 
  1.  
  1. NSNumber *expires = 
  1.  
  1. [NSNumber numberWithFloat:paramURLMustExpireInSeconds]; 
  1.  
  1. [itemDictionary setObject:expires 
  1.  
  1. forKey:CachedKeyExpiresInSeconds]; 
  1.  
  1.  
  1. } /* if (cachedFileHasExpired == NO){ */ 
  1.  
  1.  
  1. if (cachedFileIsBeingDownloaded == YES){ 
  1.  
  1. NSLog(@"这个文件已经正在下载..."); 
  1.  
  1. return(YES); 
  1.  
  1.  
  1. if (fileHasBeenCached == YES){ 
  1.  
  1. if (cachedFileHasExpired == NO && 
  1.  
  1. cachedFileExists == YES && 
  1.  
  1. cachedFileDataCanBeLoaded == YES && 
  1.  
  1. [cachedFileData length] > 0 && 
  1.  
  1. cachedFileIsFullyDownloaded == YES){ 
  1.  
  1. /* 如果文件有缓存而且没有过期 */ 
  1.  
  1. NSLog(@"文件有缓存而且没有过期."); 
  1.  
  1. [self.delegate 
  1.  
  1. cachedDownloadManagerSucceeded:self 
  1.  
  1. remoteURL:[NSURL URLWithString:paramURLAsString] 
  1.  
  1. localURL:[NSURL URLWithString:localURL] 
  1.  
  1. aboutToBeReleasedData:cachedFileData 
  1.  
  1. isCachedData:YES]; 
  1.  
  1. return(YES); 
  1.  
  1. } else { 
  1.  
  1. /* 如果文件没有被缓存,获取缓存失败 */ 
  1.  
  1. NSLog(@"文件没有缓存."); 
  1.  
  1. [self.cacheDictionary removeObjectForKey:paramURLAsString]; 
  1.  
  1. [self saveCacheDictionary]; 
  1.  
  1. } /* if (cachedFileHasExpired == NO && */ 
  1.  
  1. } /* if (fileHasBeenCached == YES){ */ 
  1.  
  1. /* 去下载文件 */ 
  1.  
  1. NSNumber *expires = 
  1.  
  1. [NSNumber numberWithFloat:paramURLMustExpireInSeconds]; 
  1.  
  1. NSMutableDictionary *newDictionary = 
  1.  
  1. [[[NSMutableDictionary alloc] init] autorelease]; 
  1.  
  1. [newDictionary setObject:expires 
  1.  
  1. forKey:CachedKeyExpiresInSeconds]; 
  1.  
  1. localURL = [paramURLAsString 
  1.  
  1. stringByAddingPercentEscapesUsingEncoding: 
  1.  
  1. NSUTF8StringEncoding]; 
  1.  
  1. localURL = [localURL stringByReplacingOccurrencesOfString:@"://" 
  1.  
  1. withString:@""]; 
  1.  
  1. localURL = [localURL stringByReplacingOccurrencesOfString:@"/" 
  1.  
  1. withString:@"{1}quot;]; 
  1.  
  1. localURL = [localURL stringByAppendingPathExtension:@"cache"]; 
  1.  
  1. NSString *documentsDirectory = 
  1.  
  1. [self documentsDirectoryWithTrailingSlash:NO]; 
  1.  
  1. localURL = [documentsDirectory 
  1.  
  1. stringByAppendingPathComponent:localURL]; 
  1.  
  1. [newDictionary setObject:localURL 
  1.  
  1. forKey:CachedKeyLocalURL]; 
  1.  
  1. [newDictionary setObject:now 
  1.  
  1. forKey:CachedKeyDownloadStartDate]; 
  1.  
  1. [self.cacheDictionary setObject:newDictionary 
  1.  
  1. forKey:paramURLAsString]; 
  1.  
  1. [self saveCacheDictionary]; 
  1.  
  1. CacheItem *item = [[[CacheItem alloc] init] autorelease]; 
  1.  
  1. [item setDelegate:self]; 
  1.  
  1. [item startDownloadingURL:paramURLAsString]; 
  1.  
  1. return(result); 
  1.  
  1.  
4、下面我们设计缓存项下载成功和失败的两个委托方法:
  1. @protocol CacheItemDelegate <NSObject>   
  1.  
  1. //下载成功执行该方法   
  1.  
  1. - (void) cacheItemDelegateSucceeded   
  1.  
  1.   :(CacheItem *)paramSender   
  1.  
  1.   withRemoteURL:(NSURL *)paramRemoteURL   
  1.  
  1.   withAboutToBeReleasedData:(NSData *)paramAboutToBeReleasedData;   
  1.  
  1. //下载失败执行该方法   
  1.  
  1. - (void) cacheItemDelegateFailed   
  1.  
  1.   :(CacheItem *)paramSender   
  1.  
  1.   remoteURL:(NSURL *)paramRemoteURL   
  1.  
  1.   withError:(NSError *)paramError;  
  1.  
  1. @end   
当我们下载成功的时候,修改缓存字典中的下载时间,表示已经下载完成,而且需要将请求的资源数据缓存到本地:
  1. //缓存项的委托方法 
  1.  
  1. - (void) cacheItemDelegateSucceeded:(CacheItem *)paramSender 
  1.  
  1. withRemoteURL:(NSURL *)paramRemoteURL 
  1.  
  1. withAboutToBeReleasedData:(NSData *)paramAboutToBeReleasedData{ 
  1.  
  1. //从缓存字典中获取该缓存项的相关数据 
  1.  
  1. NSMutableDictionary *dictionary = 
  1.  
  1. [self.cacheDictionary objectForKey:[paramRemoteURL absoluteString]]; 
  1.  
  1. //取当前时间 
  1.  
  1. NSDate *now = [NSDate date]; 
  1.  
  1. //获取有效时间 
  1.  
  1. NSNumber *expiresInSeconds = [dictionary 
  1.  
  1. objectForKey:CachedKeyExpiresInSeconds]; 
  1.  
  1. //转换成NSTimeInterval 
  1.  
  1. NSTimeInterval expirySeconds = [expiresInSeconds floatValue]; 
  1.  
  1. //修改字典中缓存项的下载结束时间 
  1.  
  1. [dictionary setObject:[NSDate date] 
  1.  
  1. forKey:CachedKeyDownloadEndDate]; 
  1.  
  1. //修改字典中缓存项的缓存过期时间 
  1.  
  1. [dictionary setObject:[now dateByAddingTimeInterval:expirySeconds] 
  1.  
  1. forKey:CachedKeyExpiryDate]; 
  1.  
  1. //保存缓存字典 
  1.  
  1. [self saveCacheDictionary]; 
  1.  
  1. NSString *localURL = [dictionary objectForKey:CachedKeyLocalURL]; 
  1.  
  1. /* 将下载的数据保持到磁盘 */ 
  1.  
  1. if ([paramAboutToBeReleasedData writeToFile:localURL 
  1.  
  1. atomically:YES] == YES){ 
  1.  
  1. NSLog(@"缓存文件到磁盘成功."); 
  1.  
  1. } else{ 
  1.  
  1. NSLog(@"缓存文件到磁盘失败."); 
  1.  
  1.  
  1. //执行缓存管理的委托方法 
  1.  
  1. [self.delegate 
  1.  
  1. cachedDownloadManagerSucceeded:self 
  1.  
  1. remoteURL:paramRemoteURL 
  1.  
  1. localURL:[NSURL URLWithString:localURL] 
  1.  
  1. aboutToBeReleasedData:paramAboutToBeReleasedData 
  1.  
  1. isCachedData:NO]; 
  1.  
  1.  
如果下载失败我们需要从缓存字典中移除改缓存项:
  1. //缓存项失败失败的委托方法 
  1.  
  1. - (void) cacheItemDelegateFailed:(CacheItem *)paramSender 
  1.  
  1. remoteURL:(NSURL *)paramRemoteURL 
  1.  
  1. withError:(NSError *)paramError{ 
  1.  
  1. /* 从缓存字典中移除缓存项,并发送一个委托 */ 
  1.  
  1. if (self.delegate != nil){ 
  1.  
  1. NSMutableDictionary *dictionary = 
  1.  
  1. [self.cacheDictionary 
  1.  
  1. objectForKey:[paramRemoteURL absoluteString]]; 
  1.  
  1. NSString *localURL = [dictionary 
  1.  
  1. objectForKey:CachedKeyLocalURL]; 
  1.  
  1. [self.delegate 
  1.  
  1. cachedDownloadManagerFailed:self 
  1.  
  1. remoteURL:paramRemoteURL 
  1.  
  1. localURL:[NSURL URLWithString:localURL] 
  1.  
  1. withError:paramError]; 
  1.  
  1.  
  1. [self.cacheDictionary 
  1.  
  1. removeObjectForKey:[paramRemoteURL absoluteString]]; 
  1.  
  1.  
5、加载缓存字典的时候,我们可以将没有下载完成的文件移除:
  1. //初始化缓存字典 
  1.  
  1. NSString *documentsDirectory = 
  1.  
  1. [self documentsDirectoryWithTrailingSlash:YES]; 
  1.  
  1. //生产缓存字典的路径 
  1.  
  1. cacheDictionaryPath = 
  1.  
  1. [[documentsDirectory 
  1.  
  1. stringByAppendingString:@"CachedDownloads.dic"] retain]; 
  1.  
  1. //创建一个NSFileManager实例 
  1.  
  1. NSFileManager *fileManager = [[NSFileManager alloc] init]; 
  1.  
  1. //判断是否存在缓存字典的数据 
  1.  
  1. if ([fileManager 
  1.  
  1. fileExistsAtPath:self.cacheDictionaryPath] == YES){ 
  1.  
  1. NSLog(self.cacheDictionaryPath); 
  1.  
  1. //加载缓存字典中的数据 
  1.  
  1. NSMutableDictionary *dictionary = 
  1.  
  1. [[NSMutableDictionary alloc] 
  1.  
  1. initWithContentsOfFile:self.cacheDictionaryPath]; 
  1.  
  1. cacheDictionary = [dictionary mutableCopy]; 
  1.  
  1. [dictionary release]; 
  1.  
  1. //移除没有下载完成的缓存数据 
  1.  
  1. [self removeCorruptedCachedItems]; 
  1.  
  1. } else { 
  1.  
  1. //创建一个新的缓存字典 
  1.  
  1. NSMutableDictionary *dictionary = 
  1.  
  1. [[NSMutableDictionary alloc] init]; 
  1.  
  1. cacheDictionary = [dictionary mutableCopy]; 
  1.  
  1. [dictionary release]; 
  1.  
  1.  
这样就基本上完成了我们需要的功能,下面看看我们如何使用我们设计的缓存功能。 例子场景: 我们用一个UIWebView来显示stackoverflow这个网站,我们在这个网站的内容缓存到本地20秒,如果在20秒内用户去请求该网站,则从本地文件中获取内容,否则过了20秒,则重新获取数据,并缓存到本地。 在界面上拖放一个button和一个webview控件,如下图。
这样我们可以很方便使用前面定义好的类。我们在viewDidLoad 中实例化一个CachedDownloadManager,并设置它的委托为self。当下载完成的时候,执行CachedDownloadManager的下载成功的委托方法。 - (void)viewDidLoad { [super viewDidLoad]; [self setTitle:@"本地缓存测试"]; CachedDownloadManager *newManager =[[CachedDownloadManager alloc] init]; self.downloadManager = newManager; [newManager release]; [self.downloadManager setDelegate:self]; } 在button的点击事件中加入下面代码,请求stackoverflow : static NSString *url = @http://stackoverflow.com; [self.downloadManager download:url urlMustExpireInSeconds:20.0fupdateExpiryDateIfInCache:YES]; 上面的代码表示将这个stackoverflow的缓存事件设置为20s,并且如果在20s内有相同的请求,则从本地获取stackoverflow的内容数据。updateExpiryDateIfInCache设置为yes表示:在此请求的时候,缓存时间又更新为20s,类似我们的session。如果设置成no,则第一次请求20s之后,该缓存就过期。 请求完成之后会执行CachedDownloadManager的委托方法。我们将数据展示在uiwebview中,代码如下: - (void) cachedDownloadManagerSucceeded:(CachedDownloadManager *)paramSender remoteURL:(NSURL *)paramRemoteURL localURL:(NSURL*)paramLocalURL aboutToBeReleasedData:(NSData *)paramAboutToBeReleasedData isCachedData:(BOOL)paramIsCachedData { [webview loadData:paramAboutToBeReleasedData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"http://stackoverflow.com"]]; } 这样我们就实现了20s的缓存。 效果: 第一次点击测试按钮:
20s内点击按钮,程序就从本地获取数据,比较快速的就显示出该网页了。
  为了节约流量,同时也是为了更好的用户体验,目前很多应用都使用本地缓存机制,其中以网易新闻的缓存功能最为出色。我自己的应用也想加入本地缓存的功能,于是我从网上查阅了相关的资料,发现总体上说有两种方法。一种是自己写缓存的处理,一种是采用ASIHTTPRequest中的ASIDownloadCache。根据我目前的技术水平和时间花费,我果断选择了后者,事实证明效果也很不错。下面说一下实现方法:     1、设置全局的Cache     在AppDelegate.h中添加一个全局变量 [plain]  @interface AppDelegate : UIResponder <UIApplicationDelegate>  {      ASIDownloadCache *myCache;  }  @property (strong, nonatomic) UIWindow *window;  @property (nonatomic,retain) ASIDownloadCache *myCache;     在AppDelegate.m中的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中添加如下代码 [plain] //自定义缓存  ASIDownloadCache *cache = [[ASIDownloadCache alloc] init];  self.myCache = cache;  [cache release];        //设置缓存路径  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  NSString *documentDirectory = [paths objectAtIndex:0];  [self.myCache setStoragePath:[documentDirectory stringByAppendingPathComponent:@"resource"]];  [self.myCache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];          在AppDelegate.m中的dealloc方法中添加如下语句 [plain]  [myCache release];      到这里为止,就完成了全局变量的声明。     2、设置缓存策略     在实现ASIHTTPRequest请求的地方设置request的存储方式,代码如下 [plain]  NSString *str = @"http://....../getPictureNews.aspx";  NSURL *url = [NSURL URLWithString:str];  ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];  //获取全局变量  AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];  //设置缓存方式  [request setDownloadCache:appDelegate.myCache];  //设置缓存数据存储策略,这里采取的是如果无更新或无法联网就读取缓存数据  [request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];  request.delegate = self;  [request startAsynchronous];      3、清理缓存数据     我在这里采用的是手动清理数据的方式,在适当的地方添加如下代码,我将清理缓存放在了应用的设置模块: [plain]  AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];  [appDelegate.myCache clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy];      这里清理的是ASICachePermanentlyCacheStoragePolicy这种存储策略的缓存数据,如果更换其他的参数的话,即可清理对应存储策略的缓存数据。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值