ICRFileCache.m 1.76 KB
Newer Older
mei's avatar
mei committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
//
//  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