// // ICRFileCache.m // XFFruit // // Created by Xummer on 15/4/13. // Copyright (c) 2015年 Xummer. All rights reserved. // #import "ICRFileCache.h" #import "NSData+EncodeAdditions.h" @interface ICRFileCache () @property (strong, nonatomic) NSCache *memCache; @end @implementation ICRFileCache + (ICRFileCache *)sharedFileCache { static dispatch_once_t once; static id instance; dispatch_once(&once, ^{ instance = [self new]; }); return instance; } - (id)init { return [self initWithNamespace:@"default"]; } - (id)initWithNamespace:(NSString *)ns { if ((self = [super init])) { NSString *fullNamespace = [@"com.xummer.ICRFileCache." stringByAppendingString:ns]; // Init the memory cache _memCache = [[NSCache alloc] init]; _memCache.name = fullNamespace; } return self; } - (void)storeFile:(NSData *)fileData forKey:(NSString *)key { if ([fileData isImageType]) { SDImageCache *cache = [SDImageCache sharedImageCache]; UIImage *image = [cache imageFromMemoryCacheForKey:key]; if (!image) { image = [[UIImage alloc] initWithData:fileData]; [cache storeImage:image forKey:key]; } } else { [self.memCache setObject:fileData forKey:key]; } } - (id)fileDataFromCacheForKey:(NSString *)key { id fileData = [self.memCache valueForKey:key]; if (fileData) { return fileData; } else { SDImageCache *cache = [SDImageCache sharedImageCache]; return [cache imageFromMemoryCacheForKey:key]; } } - (void)removeFileForKey:(NSString *)key { SDImageCache *cache = [SDImageCache sharedImageCache]; [cache removeImageForKey:key]; [self.memCache removeObjectForKey:key]; } @end