為了省流量、也為了在網路不穩時維持可用性,多數 App 都會做本地快取。做法大致分兩條路:一是使用成熟套件(例如 ASIHTTPRequest 內建的 ASIDownloadCache),二是自己寫一套輕量快取。本文聚焦在後者,因為邏輯簡單、依賴少,多數中小型專案都夠用。
第一次有網路時把資料寫入沙盒;之後每次進入頁面先判斷網路狀態——有網就請求 API 並更新快取,無網就直接讀沙盒內容顯示。
// 取得沙盒中的 Documents 路徑
NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSAllDomainsMask, YES);
NSString *path = [arr objectAtIndex:0];
NSString *pStr = [path stringByAppendingString:@"/data.txt"];
// 讀取:先取檔案內容,再反序列化
NSData *data1 = [NSData dataWithContentsOfFile:pStr];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data1];
// 寫入:把要存的物件序列化後落盤
NSArray *toSave = @[@"item1", @"item2"];
NSData *toWrite = [NSKeyedUnarchiver ...]; // 實務上用 NSKeyedArchiver
NSData *archived = [NSKeyedArchiver archivedDataWithRootObject:toSave];
[archived writeToFile:pStr atomically:YES];
快取只增不減遲早會咬到使用者的儲存空間,所以幾乎每個 App 都會在「設定」裡放一個清除快取的按鈕:
NSFileManager *fileManager = [[NSFileManager alloc] init];
[fileManager removeItemAtPath:path error:nil];
存檔位置要慎選:Documents 會被 iCloud/iTunes 備份,純快取性質的資料放 Library/Caches 更合適(系統在空間不足時也可能自行回收)。另外 NSKeyedArchiver 只能序列化實作 NSCoding 的物件,若資料量偏大或需要查詢條件,改採 SQLite 或 Core Data 會比整包檔案友善得多。最後,快取記得加上版本或時間戳記,才好實作「資料過期就重新拉取」的策略。