App 下載的圖片、設定檔、API 回應寫進沙盒之後,問題來了:怎麼知道這份快取還新不新鮮?最省事的做法是拿檔案的最後修改時間來判斷。
@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 就好,秒、分、時都能表達。