【问题标题】:Load an UIImage from Documents directory and cache it从 Documents 目录加载 UIImage 并缓存它
【发布时间】:2013-11-08 02:10:49
【问题描述】:

我在 Documents 目录中有一个UIImage。 我想加载它并缓存在内存中。

要创建和缓存 UIImage,我们应该使用+ (UIImage *)imageNamed:(NSString *)name 方法,但是这种方法的问题是图像应该在应用程序包中。当我使用其他方法时,initWithContentsOfFile,...图像没有被缓存。

如何从文档目录中加载UIImage并缓存它?

【问题讨论】:

  • 您需要为加载了imageNamed:以外的任何图像创建自己的缓存机制。
  • 你知道如何创建缓存机制吗?
  • NSDictionary 可以工作。您只需要一种在内存不足时清除缓存的方法。
  • 哦,我很愚蠢。请为我清除,谢谢您的回答。

标签: ios objective-c caching


【解决方案1】:

您可以将NSCache 添加到您的 AppDelegate,并使用如下方法:

- (UIImage *)cachedImageWithFilePath:(NSString *)path {
    // first check for a hit in the cache
    UIImage *cachedImage = [_imageCache objectForKey:path];
    if (cachedImage)
      return cachedImage;

    // load the image from disk and add to the cache
    UIImage *newImage = [[UIImage alloc] initWithContentsOfFile:path];
    [_imageCache setObject:newImage forKey:path];
    return newImage;
}

编辑:

关于NSCacheApple Documentation的文章

【讨论】:

  • @rmaddy “NSCache 基本上只是一个 NSMutableDictionary,它会自动驱逐对象以根据需要释放内存空间。无需响应内存警告或设计缓存清除计时器机制。” - 来自链接的文章
  • 对不起。我忽略了NSCache 部分,并认为您使用的是NSMutableDictionary
  • 感谢四位您的回答。接受您的回答,但我不会将该方法放入 AppDelegate :)
猜你喜欢
  • 1970-01-01
  • 2015-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-06
  • 1970-01-01
  • 2017-02-13
  • 2012-11-02
相关资源
最近更新 更多