【问题标题】:ios: image cache and retrievalios:图像缓存和检索
【发布时间】:2014-04-17 12:26:02
【问题描述】:

我希望在 iOS 中实现图像缓存功能。 我希望为此创建一个示例应用程序,只是为了我的理解。

这是我想做的:

  • 从 Internet 获取高分辨率图像并将其缓存、显示。

  • 现在下次加载这个 ViewController 时,应该从缓存而不是从 Internet 加载图像。

我知道如何使用 SDWebImage 框架缓存图像。我想用 NSCache 试试。

如何使用 NSCache 实现它?欢迎举例。

已编辑:

    - (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSCache *cache = [self imageCache];

    NSURL *url = [NSURL URLWithString:@"http://i1.ytimg.com/vi/YbT0xy_Jai0/maxresdefault.jpg"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [[UIImage alloc] initWithData:data];

    NSString *imagePath = @"http://i1.ytimg.com/vi/YbT0xy_Jai0/maxresdefault.jpg";
//    UIImage *image;
    if (!(image = [cache objectForKey:imagePath])) { // always goes inside condition
        // Cache miss, recreate image
        image = [[UIImage alloc] initWithData:data];
        if (image) {    // Insert image in cache
            [cache setObject:image forKey:imagePath]; // cache is always nil
        }
    }
    _imgCache.image = image;

【问题讨论】:

标签: ios caching


【解决方案1】:

您可以使用和 Id 将图像添加到缓存:

[imageCache setObject:image forKey:@"myImage"];

稍后您可以使用以下方法检索图像:

UIImage *image = [imageCache objectForKey:@"myImage"];

整个流程如下:

UIImage *image = [imageCache objectForKey:@"myImage"];
if (!image)
{
   // download image
   dispatch_async(dispatch_get_global_queue(0, 0), ^{
       NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:yourURL]];
       if (imageData)
       {
           // Set image to cache
           [imageCache setObject: [UIImage imageWithData:imageData] forKey:@"myImage"];
           dispatch_async(dispatch_get_main_queue(), ^{
               [yourImageView setImage:[UIImage imageWithData:imageData]];
           });
        }
    });
}
else
{
   // Use image from cache
   [yourImageView setImage:image];
}

【讨论】:

  • @z22:我已经更新了答案,你需要给动态id的
  • 非常感谢。但请检查我编辑的问题。我已经给出了我正在使用的代码。缓存始终为零,因此图像总是从互联网上下载。为什么会这样?让我知道我哪里出错了。
  • @z22: 你分配缓存了吗?如果没有,则使用:cache = [[NSCache alloc] init];
  • 我按照你说的分配了缓存,但还是一样。我哪里错了?
【解决方案2】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-15
    • 2016-01-15
    • 2019-08-29
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    相关资源
    最近更新 更多