2016-06-21 47 views
0

我已经使用sdwebimage来缓存图像。 现在imagesArr是我想要为所有单元格首先显示的图像数组。 我在后台下载图像,然后保存到磁盘,所以当我想离线模式下,我可以从磁盘中获得这些图像。图像在收集视图单元中不正确

但在某些情况下,当我滚动collectionView图像设置不正确,然后再滚动图像看起来是正确的。

这是我在cellForItemAtIndexPath中实现的以下代码。我试图调试,但似乎数据是正确的,图像名称也是正确的。

此外,collectionView在滚动中滞后。请帮我找到问题。

if(imagesArr.count>0) 
{ 
    ClothesImage *obj_image=[imagesArr objectAtIndex:0]; 
    NSString *fileName = [stringPath stringByAppendingFormat:@"/%@",obj_image.imagePath]; 
    NSLog(@"FILES NAMES %@ ", obj_image.imagePath); 
    NSData *data = [NSData dataWithContentsOfFile:fileName]; 
    if(data!=nil){ 
     UIImage *image=[UIImage imageWithData:data]; 
     cell.imgProduct.image=image; 
    } 
    else{ 
     NSString *offline=[user_defaults objectForKey:@"offline"]; 

     if([offline integerValue]==0){ 
      cell.imgProduct.image=[UIImage imageNamed:@"noImageThumb"]; 
      NSString *str_url=[NSString stringWithFormat:@"%@/%@",WEB_THUMB_IMAGE,obj_image.imagePath]; 
      str_url = [NSString stringWithFormat: @"%@",[str_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 

      [cell.imgProduct setImageWithURL:[NSURL URLWithString:str_url] placeholderImage:[UIImage imageNamed:@"noImageThumb"] options: SDWebImageRefreshCached]; 

      SDWebImageManager *manager = [SDWebImageManager sharedManager]; 
      [manager downloadWithURL:[NSURL URLWithString:str_url] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { 
       NSString *stringPathImage = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"WebThumb"]; 
       NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)]; 
       NSString *fileName = [stringPathImage stringByAppendingFormat:@"/%@",obj_image.imagePath]; 
       [data writeToFile:fileName atomically:YES]; 
       NSLog(@"DOWNLOADED IMAGE %@",fileName); 

    }]; 
     } 
     else 
     { 
      cell.imgProduct.image=[UIImage imageNamed:@"noImageThumb"]; 
     } 
    } 
} else{ 
    cell.imgProduct.image=[UIImage imageNamed:@"noImageThumb"]; 
} 
+0

不正确=错误的位置或只是noImageThumb而不是实际的图像? – Shubhank

+0

不正确的意思是一些错误的位置随机图像。 –

回答

1

我认为有几种方法可以改善这一点。

看起来您似乎在重复SDWebImage为您所做的大量工作。该库将缓存图像并按需提取它们。您应该考虑让该库预取文件到缓存中,而不是尝试预取并将它们写入磁盘。最后到-cellForRowAtIndexPath时,您只需要两种情况:一种用于在设备脱机时设置图像,另一种用于从SDWebImage提供的缓存中提取或设置图像:

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

就是这样。你所做的所有缓存和切换都不是必需的。另一件可以肯定的事情是在你的单元格子类方法-prepareForReuse中,你正在扼杀图像。

+0

所以当没有互联网时,它会自动从缓存中获取图片,来自url的absoluteString图片。 –

+0

是的,假设图像在缓存中。 – isaac