从url加载UITableViewCell图像

时间:2013-11-27 18:18:30

标签: ios iphone uitableview

我在从网址加载图片以显示在表格中时遇到问题。我目前有以下代码来处理扩展UITableViewCell的类中的图像加载:

- (void) initWithData:(NSDictionary *) data{

     NSDictionary *images = [data objectForKey:@"images"];
    __block NSString *poster = [images objectForKey:@"poster"];

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{

            NSURL *posterURL = [[NSURL alloc] initWithString:poster];
            NSData *imageData = [NSData dataWithContentsOfURL:posterURL];

            if (imageData != nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    // 4. Set image in cell
                    self.backgroundImage.image = [UIImage imageWithData:imageData];
                    [self setNeedsLayout];
                });
            }
        });


    self.backgroundImage.image = [UIImage imageNamed:@"static"];
}

tableView:cellForRowAtIndexPath:delegate中的ViewController调用initWithData方法。一切正常,直到我滚动。从我读到的,TableView单元格被回收,因为图像被异步加载,我得到的图像行错误。此外,图像不会被缓存,只要显示单元格就会再次加载

例如:滚动到中间并立即向上滚动。第一个单元格将具有与未完成加载的中间单元格对应的图像。

任何帮助或建议?非常感谢你:))

1 个答案:

答案 0 :(得分:1)

首先,正如提到的评论,我肯定会建议使用现有的框架/组件来完成这项工作。

最佳候选人可能是:

https://github.com/rs/SDWebImage

https://github.com/enormego/EGOImageLoading

或者如果您还想要一个通用网络库

https://github.com/AFNetworking/AFNetworking

也就是说,如果您仍想自己尝试,可能需要使用indexPath作为键来实现NSMutableDictionary的缓存,并将图像作为值。

假设您有一个初始化的实例变量NSMutableDictionary *imageCache

在您的cellForRowAtIndexPath方法中,在尝试进行任何图片加载之前,您会通过执行以下操作来检查您的缓存是否已有此索引的图像

if(! imageCache[indexPath])
{
  // do your web loading here, then once complete you do
  imageCache[indexPath] = // the new loaded image
}
else
{
  self.backgroundImage.image = imageCache[indexPath];
}
相关问题