您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

為 iOS 快取檔案加上有效期的實作

編輯:iOS 相關資訊

App 下載的圖片、設定檔、API 回應寫進沙盒之後,問題來了:怎麼知道這份快取還新不新鮮?最省事的做法是拿檔案的最後修改時間來判斷。

用 NSString 分類擴充檔案資訊

@implementation NSString (NSString_PathValid)

- (int)Interval {
    NSDictionary *attributes =
        [[NSFileManager defaultManager] attributesOfItemAtPath:self error:nil];

    NSString *dateString =
        [NSString stringWithFormat:@"%@", [attributes fileModificationDate]];

    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];

    NSDate *formatterDate = [inputFormatter dateFromString:dateString];

    unsigned int unitFlags = NSDayCalendarUnit;
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *d = [cal components:unitFlags
                                 fromDate:formatterDate
                                   toDate:[NSDate date]
                                  options:0];

    return [d day];
}

- (BOOL)isValid {
    if ([self Interval] < VALIDDAYS) {   // VALIDDAYS = 有效天數
        return YES;
    }
    return NO;
}

@end

使用方式

NSString *path = @"51ios/檔案路徑";

if ([path isValid]) {
    // 有效,直接使用快取
} else {
    // 已過期,重新下載
}

這段程式碼可以簡化

把 NSDate 轉成字串、再用另一個 NSDateFormatter 轉回 NSDate,中間這一趟是多余的。attributesOfItemAtPath: 回傳的字典裡 fileModificationDate 本身就是 NSDate 物件,直接拿去算差值即可:

- (BOOL)isValidWithMaxAge:(NSTimeInterval)maxAge {
    NSDictionary *attributes =
        [[NSFileManager defaultManager] attributesOfItemAtPath:self error:nil];
    NSDate *modified = attributes[NSFileModificationDate];

    if (!modified) { return NO; }   // 檔案不存在

    return -[modified timeIntervalSinceNow] < maxAge;
}

這樣寫有幾個好處:不需要 NSDateFormatter(它的建立成本不低,且與使用者地區設定相關,容易出錯);不需要 NSCalendar 逐段計算;改 accuracy 單位時只要換 maxAge 就好,秒、分、時都能表達。

幾點補充

  • 檔案不存在時:attributes 會是 nil,原寫法會得到一個奇怪的字串再算出隨機的天數。新寫法明確回傳 NO,語意清楚。
  • NSFileModificationDate 的時區:NSDate 本身不含時區概念,代表一個絕對時刻,所以 timeIntervalSinceNow 的計算不受時區影響。
  • 進階做法:如果快取內容來自 API,更可靠的作法是搭配伺服器回傳的 ETag 或 Last-Modified,用條件式請求(If-None-Match / If-Modified-Since)讓伺服器回 304,這樣既準確又省流量。檔案時間戳只能作為輔助。
  • 清理機制:有有效期就要有淘汰。實務上會在啟動時掃一次快取目錄,刪掉超過保存期限的檔案,並監看磁碟空間,避免快取把使用者儲存空間吃光。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved