[plain]
#import <Foundation/Foundation.h>
@interface CacheHelper : NSObject {
}
+ (void) setObject:(NSData *) data forKey:(NSString *) key withExpires:(int) expires;
+ (NSData *) get:(NSString *) key;
+ (void) clear;
+ (NSString *)getTempPath:(NSString*)key;
+ (BOOL)fileExists:(NSString *)filepath;
+ (BOOL)isExpired:(NSString *) key;
@end
[plain]
#import "CacheHelper.h"
[plain] view plaincopy
@implementation CacheHelper
+ (void) setObject:(NSData *) data forKey:(NSString *) key withExpires:(int) expires{
NSDate *dt = [NSDate date];
double now = [dt timeIntervalSince1970];
NSMutableString *expiresString = [[NSMutableString alloc] init];
NSData *dataExpires = [[expiresString stringByAppendingFormat:@"%f",now+expires] dataUsingEncoding:NSUTF8StringEncoding];
[expiresString release];
//創建緩存時間控制文件
[dataExpires writeToFile:[[self getTempPath:key] stringByAppendingFormat:@"%@",@".expires"] atomically:NO];
//創建緩存文件,寫入緩存
[data writeToFile:[self getTempPath:key] atomically:NO];
}
+ (NSData *) get:(NSString *) key{
if(![self fileExists:[self getTempPath:key]] || [self isExpired:[self getTempPath:key]]){
NSLog(@"no cache");
return nil;
}
NSData *data = [NSData dataWithContentsOfFile:[self getTempPath:key]];
return data;
}
+ (void) clear{
}
//獲取臨時文件目錄
+ (NSString *)getTempPath:(NSString*)key{
NSString *tempPath = NSTemporaryDirectory();
return [tempPath stringByAppendingPathComponent:key];
}
//判斷文件是否存在
+ (BOOL)fileExists:(NSString *)filepath{
NSFileManager *fileManager = [NSFileManager defaultManager];
return [fileManager fileExistsAtPath:filepath];
}
//判斷是否過期
+ (BOOL)isExpired:(NSString *) filepath{
NSData *data = [NSData dataWithContentsOfFile:[filepath stringByAppendingFormat:@"%@",@".expires"]];
NSString *expires = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
double exp = [expires doubleValue];
[expires release];
NSDate *dt = [NSDate date];
double value = [dt timeIntervalSince1970];
if(exp > value){
return NO;
}
return YES;
}
@end