设计一个移动应用的本地缓存机制

在手机应用程序开发中,为了减少与服务端的交互次数,加快用户的响应速度,一般都会在iOS设备中加一个缓存的机制,前面一篇文章介绍了iOS设备的内存缓存,这篇文章将设计一个本地缓存的机制。

功能需求

这个缓存机制满足下面这些功能。

1、可以将数据缓存到本地磁盘。

2、可以判断一个资源是否已经被缓存。如果已经被缓存,在请求相同的资源,先到本地磁盘搜索。

3、可以判断文件缓存什么时候过期。这里为了简单起见这里,我们在请求url资源的时候,给每次请求的文件设定一个过期的时间。

4、可以实现:如果文件已经被缓存,而且没有过期,这将本地的数据返回,否则重新请求url。

5、可以实现:如果文件下载不成功或者下载没有完成,下次打开程序的时候,移除这些没有成功或者没有下载完成的文件。

6、可以实现:同时请求或者下载多个资源。

设计实现:

1、设计一个CacheItem类,用来请求一个web连接,它的一个实例表示一个缓存项。这个CacheItem类,需要一个url创建一个NSURLConnection,去请求web资源。使用CacheItem类主要用来请求web资源。

  1. /*---------缓存项--------------*/
  2. @interfaceCacheItem:NSObject{
  3. @public
  4. id<CacheItemDelegate>delegate;
  5. //web地址
  6. NSString*remoteURL;
  7. @private
  8. //是否正在下载
  9. BOOLisDownloading;
  10. //NSMutableData对象
  11. NSMutableData*connectionData;
  12. //NSURLConnection对象
  13. NSURLConnection*connection;
  14. }
  15. /*--------------------------*/
  16. @property(nonatomic,retain)id<CacheItemDelegate>delegate;
  17. @property(nonatomic,retain)NSString*remoteURL;
  18. @property(nonatomic,assign)BOOLisDownloading;
  19. @property(nonatomic,retain)NSMutableData*connectionData;
  20. @property(nonatomic,retain)NSURLConnection*connection;
  21. /*----------开始下载方法-----------*/
  22. -(BOOL)startDownloadingURL:(NSString*)paramRemoteURL;
  23. @end
2、在NSURLConnection开始请求之前,调用CachedDownloadManager类,来搜索和管理本地的缓存文件。将缓存文件的情况保存到一个字典类中。这个字典设计如下:
  1. {
  2. "http://www.cnn.com"={
  3. DownloadEndDate="2011-08-0207:51:57+0100";
  4. DownloadStartDate="2011-08-0207:51:55+0100";
  5. ExpiresInSeconds=20;
  6. ExpiryDate="2011-08-0207:52:17+0100";
  7. LocalURL="/var/mobile/Applications/ApplicationID/Documents/
  8. httpwww.cnn.com.cache";
  9. };
  10. "http://www.baidu.com"={
  11. DownloadEndDate="2011-08-0207:51:49+0100";
  12. DownloadStartDate="2011-08-0207:51:44+0100";
  13. ExpiresInSeconds=20;
  14. ExpiryDate="2011-08-0207:52:09+0100";
  15. LocalURL="/var/mobile/Applications/ApplicationID/Documents/
  16. httpwww.oreilly.com.cache";
  17. };
  18. }

上面这个字典里面嵌套了字典。里面那层字典表示一个缓存项的缓存信息:下载结束时间、下载开始时间、缓存有效时间、缓存过期时间、缓存到本地的路径。

下面看下CachedDownloadManager类。用它来实现和封装我们的缓存策略。

  1. /*-----------CachedDownloadManager--------------*/
  2. @interfaceCachedDownloadManager:NSObject
  3. <CacheItemDelegate>{
  4. @public
  5. id<CachedDownloadManagerDelegate>delegate;
  6. @private
  7. //记录缓存数据的字典
  8. NSMutableDictionary*cacheDictionary;
  9. //缓存的路径
  10. NSString*cacheDictionaryPath;
  11. }
  12. @property(nonatomic,assign)
  13. id<CachedDownloadManagerDelegate>delegate;
  14. @property(nonatomic,copy)
  15. NSMutableDictionary*cacheDictionary;
  16. @property(nonatomic,retain)
  17. NSString*cacheDictionaryPath;
  18. /*保持缓存字典*/
  19. -(BOOL)saveCacheDictionary;
  20. /*公有方法:下载*/
  21. -(BOOL)download:(NSString*)paramURLAsString
  22. urlMustExpireInSeconds:(NSTimeInterval)paramURLMustExpireInSeconds
  23. updateExpiryDateIfInCache:(BOOL)paramUpdateExpiryDateIfInCache;
  24. /*--------------------------*/
  25. @end


从上面代码可以看出,这个管理缓存的类中,有一个缓存字典:cacheDictionary,用来表示所有资源的缓存情况;cacheDictionaryPath用来表示缓存的路径;saveCacheDictionary用来将缓存字典归档到本地文件中。download:urlMustExpireInSeconds:updateExpiryDateIfInCache是一个公共接口,通过传递url、缓存过期时间、是否更新缓存过期时间三个参数来方便的使用,实现我们的缓存策略。

3、如果这个文件已经被下载,而且没有过期,则从本地获取文件的数据。如果文件已经过期,则重新下载。我们通过download:urlMustExpireInSeconds:updateExpiryDateIfInCache方法来实现,主要看这个方法的代码:

  1. /*---------下载--------------*/
  2. -(BOOL)download:(NSString*)paramURLAsString
  3. urlMustExpireInSeconds:(NSTimeInterval)paramURLMustExpireInSeconds
  4. updateExpiryDateIfInCache:(BOOL)paramUpdateExpiryDateIfInCache{
  5. BOOLresult=NO;
  6. if(self.cacheDictionary==nil||
  7. [paramURLAsStringlength]==0){
  8. return(NO);
  9. }
  10. paramURLAsString=[paramURLAsStringlowercaseString];
  11. //根据url,从字典中获取缓存项的相关数据
  12. NSMutableDictionary*itemDictionary=
  13. [self.cacheDictionaryobjectForKey:paramURLAsString];
  14. /*使用下面这些变量帮助我们理解缓存逻辑*/
  15. //文件是否已经被缓存
  16. BOOLfileHasBeenCached=NO;
  17. //缓存是否过期
  18. BOOLcachedFileHasExpired=NO;
  19. //缓存文件是否存在
  20. BOOLcachedFileExists=NO;
  21. //缓存文件能否被加载
  22. BOOLcachedFileDataCanBeLoaded=NO;
  23. //缓存文件数据
  24. NSData*cachedFileData=nil;
  25. //缓存文件是否完全下载
  26. BOOLcachedFileIsFullyDownloaded=NO;
  27. //缓存文件是否已经下载
  28. BOOLcachedFileIsBeingDownloaded=NO;
  29. //过期时间
  30. NSDate*expiryDate=nil;
  31. //下载结束时间
  32. NSDate*downloadEndDate=nil;
  33. //下载开始时间
  34. NSDate*downloadStartDate=nil;
  35. //本地缓存路径
  36. NSString*localURL=nil;
  37. //有效时间
  38. NSNumber*expiresInSeconds=nil;
  39. NSDate*now=[NSDatedate];
  40. if(itemDictionary!=nil){
  41. fileHasBeenCached=YES;
  42. }
  43. //如果文件已经被缓存,则从缓存项相关数据中获取相关的值
  44. if(fileHasBeenCached==YES){
  45. expiryDate=[itemDictionary
  46. objectForKey:CachedKeyExpiryDate];
  47. downloadEndDate=[itemDictionary
  48. objectForKey:CachedKeyDownloadEndDate];
  49. downloadStartDate=[itemDictionary
  50. objectForKey:CachedKeyDownloadStartDate];
  51. localURL=[itemDictionary
  52. objectForKey:CachedKeyLocalURL];
  53. expiresInSeconds=[itemDictionary
  54. objectForKey:CachedKeyExpiresInSeconds];
  55. //如果下载开始和结束时间不为空,表示文件全部被下载
  56. if(downloadEndDate!=nil&&
  57. downloadStartDate!=nil){
  58. cachedFileIsFullyDownloaded=YES;
  59. }
  60. /*如果expiresInSeconds不为空,downloadEndDate为空,表示文件已经正在下载*/
  61. if(expiresInSeconds!=nil&&
  62. downloadEndDate==nil){
  63. cachedFileIsBeingDownloaded=YES;
  64. }
  65. /*判断缓存是否过期*/
  66. if(expiryDate!=nil&&
  67. [nowtimeIntervalSinceDate:expiryDate]>0.0){
  68. cachedFileHasExpired=YES;
  69. }
  70. if(cachedFileHasExpired==NO){
  71. /*如果缓存文件没有过期,加载缓存文件,并且更新过期时间*/
  72. NSFileManager*fileManager=[[NSFileManageralloc]init];
  73. if([fileManagerfileExistsAtPath:localURL]==YES){
  74. cachedFileExists=YES;
  75. cachedFileData=[NSDatadataWithContentsOfFile:localURL];
  76. if(cachedFileData!=nil){
  77. cachedFileDataCanBeLoaded=YES;
  78. }/*if(cachedFileData!=nil){*/
  79. }/*if([fileManagerfileExistsAtPath:localURL]==YES){*/
  80. [fileManagerrelease];
  81. /*更新缓存时间*/
  82. if(paramUpdateExpiryDateIfInCache==YES){
  83. NSDate*newExpiryDate=
  84. [NSDatedateWithTimeIntervalSinceNow:
  85. paramURLMustExpireInSeconds];
  86. NSLog(@"Updatingtheexpirydatefrom%@to%@.",
  87. expiryDate,
  88. newExpiryDate);
  89. [itemDictionarysetObject:newExpiryDate
  90. forKey:CachedKeyExpiryDate];
  91. NSNumber*expires=
  92. [NSNumbernumberWithFloat:paramURLMustExpireInSeconds];
  93. [itemDictionarysetObject:expires
  94. forKey:CachedKeyExpiresInSeconds];
  95. }
  96. }/*if(cachedFileHasExpired==NO){*/
  97. }
  98. if(cachedFileIsBeingDownloaded==YES){
  99. NSLog(@"这个文件已经正在下载...");
  100. return(YES);
  101. }
  102. if(fileHasBeenCached==YES){
  103. if(cachedFileHasExpired==NO&&
  104. cachedFileExists==YES&&
  105. cachedFileDataCanBeLoaded==YES&&
  106. [cachedFileDatalength]>0&&
  107. cachedFileIsFullyDownloaded==YES){
  108. /*如果文件有缓存而且没有过期*/
  109. NSLog(@"文件有缓存而且没有过期.");
  110. [self.delegate
  111. cachedDownloadManagerSucceeded:self
  112. remoteURL:[NSURLURLWithString:paramURLAsString]
  113. localURL:[NSURLURLWithString:localURL]
  114. aboutToBeReleasedData:cachedFileData
  115. isCachedData:YES];
  116. return(YES);
  117. }else{
  118. /*如果文件没有被缓存,获取缓存失败*/
  119. NSLog(@"文件没有缓存.");
  120. [self.cacheDictionaryremoveObjectForKey:paramURLAsString];
  121. [selfsaveCacheDictionary];
  122. }/*if(cachedFileHasExpired==NO&&*/
  123. }/*if(fileHasBeenCached==YES){*/
  124. /*去下载文件*/
  125. NSNumber*expires=
  126. [NSNumbernumberWithFloat:paramURLMustExpireInSeconds];
  127. NSMutableDictionary*newDictionary=
  128. [[[NSMutableDictionaryalloc]init]autorelease];
  129. [newDictionarysetObject:expires
  130. forKey:CachedKeyExpiresInSeconds];
  131. localURL=[paramURLAsString
  132. stringByAddingPercentEscapesUsingEncoding:
  133. NSUTF8StringEncoding];
  134. localURL=[localURLstringByReplacingOccurrencesOfString:@"://"
  135. withString:@""];
  136. localURL=[localURLstringByReplacingOccurrencesOfString:@"/"
  137. withString:@"{1}quot;];
  138. localURL=[localURLstringByAppendingPathExtension:@"cache"];
  139. NSString*documentsDirectory=
  140. [selfdocumentsDirectoryWithTrailingSlash:NO];
  141. localURL=[documentsDirectory
  142. stringByAppendingPathComponent:localURL];
  143. [newDictionarysetObject:localURL
  144. forKey:CachedKeyLocalURL];
  145. [newDictionarysetObject:now
  146. forKey:CachedKeyDownloadStartDate];
  147. [self.cacheDictionarysetObject:newDictionary
  148. forKey:paramURLAsString];
  149. [selfsaveCacheDictionary];
  150. CacheItem*item=[[[CacheItemalloc]init]autorelease];
  151. [itemsetDelegate:self];
  152. [itemstartDownloadingURL:paramURLAsString];
  153. return(result);
  154. }

4、下面我们设计缓存项下载成功和失败的两个委托方法:

  1. @protocolCacheItemDelegate<NSObject>
  2. //下载成功执行该方法
  3. -(void)cacheItemDelegateSucceeded
  4. :(CacheItem*)paramSender
  5. withRemoteURL:(NSURL*)paramRemoteURL
  6. withAboutToBeReleasedData:(NSData*)paramAboutToBeReleasedData;
  7. //下载失败执行该方法
  8. -(void)cacheItemDelegateFailed
  9. :(CacheItem*)paramSender
  10. remoteURL:(NSURL*)paramRemoteURL
  11. withError:(NSError*)paramError;
  12. @end


当我们下载成功的时候,修改缓存字典中的下载时间,表示已经下载完成,而且需要将请求的资源数据缓存到本地:

  1. //缓存项的委托方法
  2. -(void)cacheItemDelegateSucceeded:(CacheItem*)paramSender
  3. withRemoteURL:(NSURL*)paramRemoteURL
  4. withAboutToBeReleasedData:(NSData*)paramAboutToBeReleasedData{
  5. //从缓存字典中获取该缓存项的相关数据
  6. NSMutableDictionary*dictionary=
  7. [self.cacheDictionaryobjectForKey:[paramRemoteURLabsoluteString]];
  8. //取当前时间
  9. NSDate*now=[NSDatedate];
  10. //获取有效时间
  11. NSNumber*expiresInSeconds=[dictionary
  12. objectForKey:CachedKeyExpiresInSeconds];
  13. //转换成NSTimeInterval
  14. NSTimeIntervalexpirySeconds=[expiresInSecondsfloatValue];
  15. //修改字典中缓存项的下载结束时间
  16. [dictionarysetObject:[NSDatedate]
  17. forKey:CachedKeyDownloadEndDate];
  18. //修改字典中缓存项的缓存过期时间
  19. [dictionarysetObject:[nowdateByAddingTimeInterval:expirySeconds]
  20. forKey:CachedKeyExpiryDate];
  21. //保存缓存字典
  22. [selfsaveCacheDictionary];
  23. NSString*localURL=[dictionaryobjectForKey:CachedKeyLocalURL];
  24. /*将下载的数据保持到磁盘*/
  25. if([paramAboutToBeReleasedDatawriteToFile:localURL
  26. atomically:YES]==YES){
  27. NSLog(@"缓存文件到磁盘成功.");
  28. }else{
  29. NSLog(@"缓存文件到磁盘失败.");
  30. }
  31. //执行缓存管理的委托方法
  32. [self.delegate
  33. cachedDownloadManagerSucceeded:self
  34. remoteURL:paramRemoteURL
  35. localURL:[NSURLURLWithString:localURL]
  36. aboutToBeReleasedData:paramAboutToBeReleasedData
  37. isCachedData:NO];
  38. }

如果下载失败我们需要从缓存字典中移除改缓存项:
  1. //缓存项失败失败的委托方法
  2. -(void)cacheItemDelegateFailed:(CacheItem*)paramSender
  3. remoteURL:(NSURL*)paramRemoteURL
  4. withError:(NSError*)paramError{
  5. /*从缓存字典中移除缓存项,并发送一个委托*/
  6. if(self.delegate!=nil){
  7. NSMutableDictionary*dictionary=
  8. [self.cacheDictionary
  9. objectForKey:[paramRemoteURLabsoluteString]];
  10. NSString*localURL=[dictionary
  11. objectForKey:CachedKeyLocalURL];
  12. [self.delegate
  13. cachedDownloadManagerFailed:self
  14. remoteURL:paramRemoteURL
  15. localURL:[NSURLURLWithString:localURL]
  16. withError:paramError];
  17. }
  18. [self.cacheDictionary
  19. removeObjectForKey:[paramRemoteURLabsoluteString]];
  20. }
5、加载缓存字典的时候,我们可以将没有下载完成的文件移除:
[plain] view plaincopy
  1. //初始化缓存字典
  2. NSString*documentsDirectory=
  3. [selfdocumentsDirectoryWithTrailingSlash:YES];
  4. //生产缓存字典的路径
  5. cacheDictionaryPath=
  6. [[documentsDirectory
  7. stringByAppendingString:@"CachedDownloads.dic"]retain];
  8. //创建一个NSFileManager实例
  9. NSFileManager*fileManager=[[NSFileManageralloc]init];
  10. //判断是否存在缓存字典的数据
  11. if([fileManager
  12. fileExistsAtPath:self.cacheDictionaryPath]==YES){
  13. NSLog(self.cacheDictionaryPath);
  14. //加载缓存字典中的数据
  15. NSMutableDictionary*dictionary=
  16. [[NSMutableDictionaryalloc]
  17. initWithContentsOfFile:self.cacheDictionaryPath];
  18. cacheDictionary=[dictionarymutableCopy];
  19. [dictionaryrelease];
  20. //移除没有下载完成的缓存数据
  21. [selfremoveCorruptedCachedItems];
  22. }else{
  23. //创建一个新的缓存字典
  24. NSMutableDictionary*dictionary=
  25. [[NSMutableDictionaryalloc]init];
  26. cacheDictionary=[dictionarymutableCopy];
  27. [dictionaryrelease];
  28. }
这样就基本上完成了我们需要的功能,下面看看我们如何使用我们设计的缓存功能。

例子场景:

我们用一个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.0f
    updateExpiryDateIfInCache: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内点击按钮,程序就从本地获取数据,比较快速的就显示出该网页了。

设计一个移动应用的本地缓存机制

总结:

本文通过代码和实例设计了一个iPhone应用程序本地缓存的方案。当然这个方案不是最好的,如果你有更好的思路,欢迎告诉我。