[英]Image caching for images in the Documents directory
我的应用程序通过HTTP下载带有图像的软件包。 它们存储在Documents /目录中并显示。
我读到UIImage不适用于在iphone / ipad的“ ... / Documents /”目录中缓存图像(因为仅[UIImage imageNamed:]使用缓存,并且仅适用于捆绑包中的图像)。 另外,我希望能够在下载新程序包时清除缓存。
所以,这是我写的:
在Image.h中
#import <Foundation/Foundation.h>
@interface Image : NSObject
+(void) clearCache;
+(UIImage *) imageInDocuments:(NSString *)imageName ;
+(void)addToDictionary:(NSString *)imageName image:(UIImage *)image;
@end
在Image.m中
#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
我写它是为了提高加载图像的性能。 但是我不确定实现。 我不想产生相反的效果:
你怎么看 ? 尴尬吗?
ps:我把代码放到了gist.github上: https ://gist.github.com/1719871
哇...您正在实现自己的对象缓存? 您是否首先看过NSCache以确定它是否适合您的需求?
(我不相信UIImage符合NSDiscardableContent,因此,如果您希望缓存处理低内存条件,则必须自己清除缓存或包装UIImage。但是正如您在问题中指出的那样,当前的实现并没有要么这样做。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.