Skip to content

Instantly share code, notes, and snippets.

@arnauddelattre
Created February 1, 2012 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arnauddelattre/1719871 to your computer and use it in GitHub Desktop.
Save arnauddelattre/1719871 to your computer and use it in GitHub Desktop.
Image caching for images in the Documents directory
#import <Foundation/Foundation.h>
@interface Image : NSObject
+(void) clearCache;
+(UIImage *) imageInDocuments:(NSString *)imageName ;
+(void)addToDictionary:(NSString *)imageName image:(UIImage *)image;
@end
#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