Created
February 1, 2012 22:28
-
-
Save arnauddelattre/1719871 to your computer and use it in GitHub Desktop.
Image caching for images in the Documents directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface Image : NSObject | |
+(void) clearCache; | |
+(UIImage *) imageInDocuments:(NSString *)imageName ; | |
+(void)addToDictionary:(NSString *)imageName image:(UIImage *)image; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "Image.h" | |
@implementation Image | |
static NSDictionary * cache; | |
static NSDictionary * fifo; | |
static NSNumber * indexFifo; | |
static NSInteger maxFifo = 25; | |
+(void)initialize { | |
[self clearCache]; | |
} | |
+(void) clearCache { | |
cache = [[NSDictionary alloc] init]; | |
fifo = [[NSDictionary alloc] init]; | |
indexFifo = [NSNumber numberWithInt:0]; | |
} | |
+(UIImage *) imageInDocuments:(NSString *)imageName { | |
UIImage * imageFromCache = [cache objectForKey:imageName]; | |
if(imageFromCache != nil) return imageFromCache; | |
NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%@", imageName, nil]]; | |
UIImage * result = [UIImage imageWithContentsOfFile:path]; | |
[self addToDictionary:imageName image:result]; | |
return result; | |
} | |
+(void)addToDictionary:(NSString *)imageName image:(UIImage *)image { | |
NSMutableDictionary *mFifo = [fifo mutableCopy]; | |
NSString * imageToRemoveFromCache = [mFifo objectForKey:indexFifo]; | |
[mFifo setObject:imageName forKey:indexFifo]; | |
fifo = [NSDictionary dictionaryWithDictionary:mFifo]; | |
// indexFifo is like a cursor which loop in the range [0..maxFifo]; | |
indexFifo = [NSNumber numberWithInt:([indexFifo intValue] + 1) % maxFifo]; | |
NSMutableDictionary * mcache = [cache mutableCopy]; | |
[mcache setObject:image forKey:imageName]; | |
if(imageToRemoveFromCache != nil) [mcache removeObjectForKey:imageToRemoveFromCache]; | |
cache = [NSDictionary dictionaryWithDictionary:mcache]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment