我的應用程序通過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