【问题标题】:Image caching for images in the Documents directoryDocuments 目录中图像的图像缓存
【发布时间】: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


【解决方案1】:

哇...您正在实现自己的对象缓存吗?你有没有先看看NSCache,看看它是否适合你的需求?

(我不相信 UIImage 符合 NSDiscardableContent,因此如果您希望缓存处理低内存条件,则必须自己清除缓存或包装 UIImage。但是正如您在问题中指出的那样,您当前的实现也不这样做。)

【讨论】:

  • 谢谢,我不知道 NSCache。我会用它做一些测试。而不是包装 UIImage 也许我可以: 1)在我的 Image 类中包装 NSCache 。 2)所以我可以删除我的 2 NSDictionary(和 nsinteger)。 3)当调用[Image clearCache]时,只需调用NSCache方法[x removeAllObjects]。对我来说似乎更容易。
猜你喜欢
  • 2020-02-20
  • 1970-01-01
  • 2014-08-23
  • 1970-01-01
  • 2017-07-29
  • 2017-07-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-03
相关资源
最近更新 更多