2012-02-01 73 views
0

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

+0

哦,我纠正了一些错误。根本没有使用缓存(缺少对addToDictionary的调用)。这使其他错误变得更加明显。 – 2012-02-01 22:44:10

回答

3

哇......你实现你自己的对象缓存?你先看看NSCache看看它是否适合你的需求?我不相信UIImage符合NSDiscardableContent,所以你必须自己清除缓存或者包装UIImage,如果你想让缓存处理内存不足的情况,但正如你在你的问题中提到的那样,你的当前实施不这样做)

+0

谢谢,我不知道NSCache。我会用它做一些测试。也许我可以:1)在我的Image类中包装NSCache。 2)所以我可以删除我的2 NSDictionary(和nsinteger)。 3)当调用[Image clearCache]时,只需调用NSCache方法[x removeAllObjects]。对我来说似乎更容易。 – 2012-02-01 23:02:23