基于jsonkit,缓存(缓存对象 是服务器返回的整个json字符串)工具类,
#import "CacheUtil.h"
#import "JSONKit.h"
@implementation CacheUtil
//获得访问目录
+ (NSString*)documentPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
//写缓存
+ (void)writeCache:(id)json ofType:(NSString *)type
{
NSString* content = [json JSONString];
[content writeToFile:[[CacheUtildocumentPath] stringByAppendingPathComponent:type] atomically:YESencoding:NSUTF8StringEncodingerror:nil];
}
//读缓存
+ (id)readCacheOfType:(NSString *)type
{
NSString* path = [[CacheUtildocumentPath] stringByAppendingPathComponent:type];
if (![[NSFileManagerdefaultManager] fileExistsAtPath:path]) {
return nil;
}
NSError* error;
NSData* content = [[NSData alloc] initWithContentsOfFile:path];
if (error) {
return nil;
}
id json = [content objectFromJSONData];
return json;
}
//清除缓存
+ (void)clearCacheOfType:(NSString*)type
{
NSString* path = [[CacheUtildocumentPath] stringByAppendingPathComponent:type];
if ([[NSFileManagerdefaultManager] fileExistsAtPath:path]) {
[[NSFileManagerdefaultManager] removeItemAtPath:path error:nil];
}
}
@end