图像缓存文档目录中的图像

时间:2012-02-01 22:31:14

标签: iphone objective-c ios ipad caching

我的应用程序通过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

1 个答案:

答案 0 :(得分:3)

哇...你在实现自己的对象缓存吗?您是否先看过NSCache以确定它是否符合您的需求?

(我不相信UIImage符合NSDiscardableContent,所以如果你想让缓存处理低内存条件,你必须自己清除缓存或者包装UIImage。但正如你在问题中所说,你当前的实现也不这样做。)