Skip to content

Instantly share code, notes, and snippets.

@skram
Created June 6, 2012 06:16
Show Gist options
  • Save skram/2880240 to your computer and use it in GitHub Desktop.
Save skram/2880240 to your computer and use it in GitHub Desktop.
UIImage extension, with custom cache control.
//
// UIImage+Cache.m
//
// Created by Mark on 6/6/12.
// Copyright (c) 2012 skram devs LLC. All rights reserved.
// http://skr.am
#import <UIKit/UIKit.h>
@interface UIImage(Cache)
/* Used to free all allocated memory for cache */
+(void)freeCache;
/* The usual, horrible -imageNamed: turned pretty. */
+(UIImage*)imageNamed:(NSString*)name;
/* With this you can choose if you want the images stored in the cache to autorelease*/
+(void)setShouldAutorelease:(BOOL)value;
@end
//
// UIImage+Cache.m
//
// Created by Mark on 6/6/12.
// Copyright (c) 2012 skram devs LLC. All rights reserved.
// http://skr.am
#import "UIImage+Cache.h"
static NSMutableDictionary *_cache = nil;
static BOOL autoReleaseImages = FALSE;
@implementation UIImage(Cache)
+(void)setShouldAutorelease:(BOOL)value {
autoReleaseImages = value;
}
+(void)freeCache {
if (_cache != nil) {
NSLog(@"Cache Freed %@", _cache);
[_cache release];
_cache = nil;
}
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
+(UIImage*)imageNamed:(NSString*)name {
if(_cache == nil)
_cache = [[NSMutableDictionary alloc] init];
if([_cache objectForKey:name] != nil)
return (UIImage*)[_cache objectForKey:name];
NSString *filePath = nil;
if([name hasPrefix:@"/"]) {
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
filePath = [name copy];
name = [name lastPathComponent];
} else {
NSArray *comps = [name componentsSeparatedByString:@"."];
filePath = [[NSBundle mainBundle] pathForResource:[comps objectAtIndex:0]
ofType:[comps objectAtIndex:1]];
}
UIImage *image = nil;
if(autoReleaseImages)
image = [[UIImage imageWithContentsOfFile:filePath] autorelease];
else
image = [UIImage imageWithContentsOfFile:filePath];
[filePath release];
NSAssert(image, @"Image Not Found");
[_cache setObject:image forKey:[name lastPathComponent]];
return image;
}
#pragma clang diagnostic pop
@end
@demonnico
Copy link


if(autoReleaseImages)
image = [[UIImage imageWithContentsOfFile:filePath] autorelease];
else
image = [UIImage imageWithContentsOfFile:filePath];


what's the different between that two methods?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment