【问题标题】:Cache NSData(with UIImages)缓存 NSData(带有 UIImages)
【发布时间】:2012-07-06 16:19:40
【问题描述】:

目前,我正在为该网站开发客户端。我有大量的图像需要加载到我的 TableView 中。这是我正在做的事情:

NSDictionary *propertyItems = [self.items objectAtIndex:indexPath.row];
    cell.fio.font = [UIFont boldSystemFontOfSize:17.0f];

    if([propertyItems objectForKey:@"online"] == [NSNumber numberWithInt:1])
        cell.fio.textColor = [UIColor colorWithRed:0.3 green:0.6 blue:0.3 alpha:1.0];

    dispatch_queue_t downloadPhotosQueue = dispatch_queue_create("downloadPhotosQeue", NULL);
    dispatch_async(downloadPhotosQueue, ^{
        NSData *photosData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.example.com/%@", [propertyItems objectForKey:@"photo_trumb"]]]];
        dispatch_async(dispatch_get_main_queue(), ^{
            cell.pic.image = [UIImage imageWithData:photosData];
        });

    });

    cell.fio.text = [propertyItems objectForKey:@"fio"];

我在 cellForRowAtIndexPath: 方法中执行此操作。 一切都在快速加载。但问题是,当我向下滚动表格并再次向上滚动时,图像会一遍又一遍地重新加载。

问题:有什么方法可以轻松缓存我从服务器获取的 UIImages?因此,如果它们被加载一次,它们就不会在我运行应用程序时一遍又一遍地重新加载。也许我做错了什么?

提前致谢!

【问题讨论】:

    标签: objective-c xcode multithreading uitableview uiimageview


    【解决方案1】:

    我强烈推荐AsyncImageView。我使用它,它就像一个魅力。只需设置图片 url,它就会自己处理一切。

    AsyncImageView *imageView = [[AsyncImageView alloc]init];
    imageView.imageURL = [NSURL URLWithString:@"https://www.google.es/logos/classicplus.png"];
    

    它将图像缓存在内存中,因此不会再次从服务器检索它。当收到内存警告时,它也会释放它们。

    【讨论】:

      【解决方案2】:

      要从网站加载图像,我使用AFNetworking。它提供了一个从 URL 加载图像的类:

      首先将#import "UIImageView+AFNetworking" 添加到顶部 控制器或视图实现文件。此类别添加方法 到 UIImageView,比如:

      [imageView setImageWithURL:[NSURL URLWithString:@"…"]];

      【讨论】:

        【解决方案3】:

        我推荐this 库来完成你想要的。

        cellForRowAtIndexPath:

            [cell.imageView setImageWithURL:
            [NSURL URLWithString:[NSString stringWithString:@"www.yourimagepath.path"]]
              placeholderImage:[UIImage imageNamed:@"no_image.jpg"]];
        

        库将为您缓存图像。还可以设置图片的setHolder,这样在下载图片的时候就不会像空白图片了。

        【讨论】:

          【解决方案4】:

          问题就在这里:

          NSData *photosData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.example.com/%@", [propertyItems objectForKey:@"photo_trumb"]]]];
          

          dataWithContentsOfURL

          每次调用函数时(每次滚动)都会向 URL 发起请求。 您需要在 cellForRowAtIndexPath 之前加载所有图片。 就像在 ViewDidLoad 中一样。 您可以将它们存储在一个数组中,然后在 cellForRowAtIndexPath 中显示您的图片数组。

          如果像你说的那样加载真的很快:jsut load picture Once in CellForRowAtIndexPath.将它们存储在 mutableArray 中。并检查图片是否已经存在。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-03-15
            相关资源
            最近更新 更多