【IOS自定义工具类之缓存助手类】CacheHelper

#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
#import "CacheHelper.h"


@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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值