【发布时间】:2012-02-01 22:31:14
【问题描述】:
我的应用程序通过 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
我写它是为了提高加载图像的性能。但我不确定实施。我不想产生相反的效果:
- 有很多复制(从可变字典到不可变字典,反之亦然)
- 不知道如何选择合适的maxFifo值。
- 你认为我需要处理内存警告并在它发生时清除缓存吗?
你怎么看?尴尬吗?
ps:我把代码放在 gist.github 上:https://gist.github.com/1719871
【问题讨论】:
-
哦,我纠正了一些错误。根本没有使用缓存(缺少对 addToDictionary 的调用)。这突出了其他错误。
标签: iphone objective-c ios ipad caching