2017-07-15 56 views
1

我有一个集合视图,需要显示其文件保存在设备上的图像集合。它们都是600x600像素,所以我认为最好在后台线程上异步创建UIImage,然后在主线程上设置我的UIImageViewimage属性。下面是我在一段时间image做到这一点凡在我(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath方法UICollectionViewCell使用GCD从设备加载异步图像

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 

     NSString *imageName = [NSString stringWithFormat:@"wo-%@", template.fileName]; 

     UIImage *image = [UIImage imageNamed:imageName]; 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      if (image == nil) 
      { 
       self.collectionView.backgroundColor = [UIColor redColor]; 
       NSLog(@"image named: %@ in nil!", imageName); 
      } 
      cell.imageView.image = image; 
     }); 
    }); 

    return cell; 

每隔一段时间就会nil的细胞之一。它不可重现,并不总是相同的单元/图像名称。我想知道这与使用UIImage imageNamed:方法有什么关系,或者我错误地使用了GCD?任何关于这个问题的想法将不胜感激。

+0

使用imageNamed意味着图像随您的应用程序的包。直接加载这些应该有非常低的延迟(甚至在第一次加载之后更低,因为它们将被UIImage缓存)。您可以/也应该考虑运送较小版本的图像,并针对该设备进行优化。跳过gcd代码,只需调用imageNamed: – danh

回答

0

对于异步加载图像,“SDWebImage”可能是最佳解决方案。

SDWebImage

只是叫你cellForItemAtIndexPath下面的方法:

[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.example.com/path/to/image.jpg"] 
     placeholderImage:[UIImage imageNamed:@"placeholder.png"]];