关于加载图片太多的问题

处理网络图片缓存步骤:
1、根据图片URL查找内存是否有这张图片,有则返回图片,没有则进入第二步
2、查找物理存储是否有这张图片,有则返回图片,没有则进入第三步
3、从网络上下载该图片,下载完后保存到内存和物理存储上,并返回该图片
注:因为URL包含特殊字符和长度不确定,要对URL进行MD5处理或其他处理

下面是针对以上步骤的代码讲解:
1、内存缓存图片处理
      使用NSMutableDictionary存储图片UIImage,数组的Key为该图片的URL地址
//缓存图片到内存上
1. [memCache setObject:image forKey:key];  
2、物理缓存图片处理
      把图片保持到物理存储设备上,则直接使用NSFileManager,把URL作为文件名保存
 3、网络图片下载处理
       图片使用异步下载,下载完后把图片保持到NSMutableDictionary和物理存储上

(1)最简单的下载,显示图片的方法

[plain] view plaincopy

  1.    UIImageView *imageView = [[UIImageView alloc] initWithFrame:[self.view bounds]];  
  2.    imageView.image = [self loadImageFromUrl:@"http://storage.live.com/items/72A00BF5A838647C!1616?filename=meinv004.jpg"];  
  3.    [self.view addSubview:imageView];  
  4.      
  5.    -(UIImage*)loadImageFromUrl: (NSString*)url  
  6. {  
  7.     NSURL  *imageUrl = [NSURL URLWithString:url];  
  8.     NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];  
  9.     UIImage *image = [UIImage imageWithData:imageData];  
  10.     return image;  
  11. }  

    
这种最简单的图片加载方式阻塞了main线程. 使得流程不能流畅进行.


(2)开辟线程来解决这个问题.

[plain] view plaincopy

  1.    // set imageview  
  2.    UIImageView *imageView = [[UIImageView alloc] initWithFrame:[self.view bounds]];  
  3.    imageView.backgroundColor = [UIColor yellowColor];  
  4.    imageView.tag = imageView_tag;  
  5.    [self.view addSubview:imageView];  
  6.      
  7.    // load image in background  
  8.    NSString *url = IMAGE_URL;  
  9.    [self performSelectorInBackground:@selector(loadImageFromUrl:) withObject:url];  
  10.      
  11.   
  12.   
  13. -(void)loadImageFromUrl: (NSString*)url {  
  14.     NSURL  *imageUrl = [NSURL URLWithString:url];  
  15.     NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];  
  16.     [self performSelectorOnMainThread:@selector(updateImageView:) withObject:imageData waitUntilDone:NO];  
  17. }  
  18. -(void) updateImageView:(NSData*) data {  
  19.     UIImageView *imageView = (UIImageView *)[self.view viewWithTag:imageView_tag];  
  20.     imageView.image = [UIImage imageWithData:data];  
  21. }  



并且只能在main线程中设置UI的内容, 所以代码量增加了较多. 代码量暂且不管, 这里还有一个比较严重的问题就是每次都要加载图片


使用SDWebImage: 

[plain] view plaincopy

  1. #import <SDWebImage/UIImageView+WebCache.h>  
  2. [imageView setImageWithURL:[NSURL URLWithString:[_objects objectAtIndex:indexPath.row]]  
  3.                   placeholderImage:[UIImage imageNamed:@"placeholder.png"]];  

SDWebImage可以实现
*下载和缓存图片.
*相同的url不会被重复下载.

*坏的url不会一直请求.

原文地址:https://www.cnblogs.com/GhostKZShadow/p/5105551.html