iphone - Documents 目录中图像的图像缓存

标签 iphone objective-c ios ipad caching

我的应用程序通过 HTTP 下载带有图像的包。它们存储在 Documents/目录中,并显示。

我读到 UIImage 无法在 iphone/ipad 的“.../Documents/”目录中缓存图像(因为只有 [UIImage imageNamed:] 使用缓存,并且它仅适用于图像在 bundle 中)。此外,我希望能够在下载新包时清除缓存。

所以,这是我写的:

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

最佳答案

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

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

关于iphone - Documents 目录中图像的图像缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9104373/

相关文章:

ios - dataWithContentsOfFile 返回空

ios - 在iOS 7中更改键盘上方的自定义UIToolbar的颜色(而不仅仅是更改文本颜色)

ios - UNCalendarNotificationTrigger 每小时触发器返回错误的触发日期

iphone - 尽快显示 CGImage 数据流

ios - 将 NSPersistentStore 从应用程序沙箱迁移到共享组容器

ios - 旋转时 layer.border 上的线条不平滑

iphone - 查找不区分大小写的相似字符串 - iPhone

ios - Objective-C 查找方法的调用者

ios - Objective-c UIDocumentInteractionController 加载灰屏

ios - Swift 链接器错误 : Undefined symbol for surely available API presentationDimensions