当前位置:编程学习 > wap >>

[IOS自定义工具类之缓存助手类]CacheHelper

[plain] 
#import <Foundation/Foundation.h>  
  
  
@inte易做图ce 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  
 
补充:移动开发 , IOS ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,