1. 程式人生 > >iOS開發本地快取(資料離線快取、讀取、釋放)

iOS開發本地快取(資料離線快取、讀取、釋放)

1、設定全域性的Cache
    在AppDelegate.h中新增一個全域性變數

  1. @interface AppDelegate : UIResponder   
  2. {  
  3.     ASIDownloadCache *myCache;  
  4. }  
  5. @property (strong, nonatomic) UIWindow *window;  
  6. @property (nonatomic,retain) ASIDownloadCache *myCache;  

   在AppDelegate.m中的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(
NSDictionary *)launchOptions方法中新增如下程式碼
  1. //自定義快取  
  2. ASIDownloadCache *cache = [[ASIDownloadCache alloc] init];  
  3. self.myCache = cache;  
  4. [cache release];  
  5. //設定快取路徑  
  6. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  7. NSString *documentDirectory = [paths objectAtIndex:0];  
  8. [self.myCache setStoragePath:[documentDirectory stringByAppendingPathComponent:@"resource"]];  
  9. [self.myCache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];  

    在AppDelegate.m中的dealloc方法中新增如下語句

  1. [myCache release];  

    到這裡為止,就完成了全域性變數的宣告。

    2、設定快取策略

    在實現ASIHTTPRequest請求的地方設定request的儲存方式,程式碼如下

  1. NSString *str = @"http://....../getPictureNews.aspx";  
  2. NSURL *url = [NSURL URLWithString:str];  
  3. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];  
  4. //獲取全域性變數  
  5. AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];  
  6. //設定快取方式  
  7. [request setDownloadCache:appDelegate.myCache];  
  8. //設定快取資料儲存策略,這裡採取的是如果無更新或無法聯網就讀取快取資料  
  9. [request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];  
  10. request.delegate = self;  
  11. [request startAsynchronous];  

    3、清理快取資料

    我在這裡採用的是手動清理資料的方式,在適當的地方新增如下程式碼,我將清理快取放在了應用的設定模組:

  1. AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];  
  2. [appDelegate.myCache clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy];  
    這裡清理的是ASICachePermanentlyCacheStoragePolicy這種儲存策略的快取資料,如果更換其他的引數的話,即可清理對應儲存策略的快取資料。