I know that the -imageNamed: method returns a Cached UIImage, but the problem is that my image file is stored in \'Documents\', and the -imageNamed: method seems to only search
The simplest way would be an NSMutableDictionary
storing the cached images and a clear cache method:
@interface UIImage (CacheExtensions)
+ (id)cachedImageWithContentsOfFile:(NSString *)path;
+ (void)clearCache;
@end
static NSMutableDictionary *UIImageCache;
@implementation UIImage (CacheExtensions)
+ (id)cachedImageWithContentsOfFile:(NSString *)path
{
id result;
if (!UIImageCache)
UIImageCache = [[NSMutableDictionary alloc] init];
else {
result = [UIImageCache objectForKey:path];
if (result)
return result;
}
result = [UIImage imageWithContentsOfFile:path];
[UIImageCache setObject:result forKey:path];
return result;
}
+ (void)clearCache
{
[UIImageCache removeAllObjects];
}
@end
Note: you should call +[UIImage clearCache]
from your didReceiveMemoryWarning
method. Also, clearCache
will invalidate all objects in the cache, not just unused items; a UIImage
subclass and more complicated caching mechanism would be required to remedy this.