你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> [IOS自定義工具類之緩存助手類]CacheHelper

[IOS自定義工具類之緩存助手類]CacheHelper

編輯:IOS開發綜合
[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    
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved