Skip to content

Instantly share code, notes, and snippets.

@sachithkadamba
Created November 25, 2012 05:44
Show Gist options
  • Save sachithkadamba/4142530 to your computer and use it in GitHub Desktop.
Save sachithkadamba/4142530 to your computer and use it in GitHub Desktop.
Custom caching for + (UIImage *)imageNamed:(NSString *)name
//UIImage+Cache.h
#import <UIKit/UIKit.h>
@interface UIImage (Cache)
+ (UIImage *)imageNamed:(NSString *)name;
+ (void)freeCache;
+ (BOOL)freeCacheOnMemoryWarning;
+ (void)setFreeCacheOnMemoryWarning:(BOOL)freeCacheOnMemoryWarning;
@end
//UIImage+Cache.m
#import "UIImage+Cache.h"
static NSMutableDictionary *_cache;
static BOOL _freeCacheOnMemoryWarning;
@implementation UIImage (Cache)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
+ (UIImage *)imageNamed:(NSString *)name
{
NSAssert(name, @"[UIImage+Cache imageNamed:%@]: image not found!", name);
NSString *path = name.stringByDeletingLastPathComponent;
NSString *fileName = name.lastPathComponent;
NSArray *comps = [fileName componentsSeparatedByString:@"."];
NSString *type = @"png";
if (comps.count > 1)
{
type = comps.lastObject;
fileName = [fileName substringWithRange:NSMakeRange(0, fileName.length - type.length - 1)];
}
else
fileName = [comps objectAtIndex:0];
path = [path stringByAppendingPathComponent:fileName];
UIImage *image = (UIImage*)[_cache objectForKey:path];
if (image)
return image;
image = [UIImage.alloc initWithContentsOfFile:[NSBundle.mainBundle pathForResource:path ofType:type]];
NSAssert(image, @"[UIImage+Cache imageNamed:@\"%@\"]: image not found!", name);
if (!_cache)
_cache = NSMutableDictionary.new;
[_cache setObject:image forKey:path];
return image;
}
#pragma clang diagnostic pop
+ (void)freeCache
{
NSLog(@"[UIImage+Cache freeCache]:\n%@", _cache);
_cache = nil;
}
+ (BOOL)freeCacheOnMemoryWarning
{
return _freeCacheOnMemoryWarning;
}
+ (void)setFreeCacheOnMemoryWarning:(BOOL)freeCacheOnMemoryWarning
{
if (freeCacheOnMemoryWarning)
if (!_freeCacheOnMemoryWarning)
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(freeCache) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
else;
else
if (_freeCacheOnMemoryWarning)
[NSNotificationCenter.defaultCenter removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
_freeCacheOnMemoryWarning = freeCacheOnMemoryWarning;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment