我的应用程序通过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
我写的,以改善负载性能图片。但我不确定实施。我不希望有相反的效果:
- 有很多重新复制的(从可变百科到unmutable和对面)
- 我不知道该如何选择合适的maxFifo值。
- 您是否认为我需要处理内存警告并清除缓存?
您怎么看?它很尴尬吗?
PS:我把代码放在gist.github:https://gist.github.com/1719871
哦,我纠正了一些错误。根本没有使用缓存(缺少对addToDictionary的调用)。这使其他错误变得更加明显。 – 2012-02-01 22:44:10