ios UIImageView异步加载网络图片

方法1:在UI线程中同步加载网络图片

  1. UIImageView *headview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];  
  2.   
  3. NSURL *photourl = [NSURL URLWithString:@"http://www.exampleforphoto.com/pabb/test32.png"];  
  4. //url请求实在UI主线程中进行的  
  5. UIImage *images = [UIImage imageWithData:[NSData dataWithContentsOfURL:photourl]];//通过网络url获取uiimage  
  6. headview.image = images;  

这是最简单的,但是由于在主线程中加载,会阻塞UI主线程。所以可以试试NSOperationQueue,一个NSOperationQueue 操作队列,就相当于一个线程管理器,而非一个线程。因为你可以设置这个线程管理器内可以并行运行的的线程数量等等。

 

方法2:使用NSOperationQueue异步加载

  1. 下面就是使用NSOperationQueue实现子线程加载图片:  
  2. - (void)viewDidLoad  
  3. {  
  4.     [super viewDidLoad];  
  5.       
  6.     NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];  
  7.       
  8.     self.imageview  = [[[UIImageView alloc] initWithFrame:CGRectMake(110, 50, 100, 100)] autorelease];  
  9.     [self.imageview setBackgroundColor:[UIColor grayColor]];  
  10.     [self.view addSubview:self.imageview];  
  11.       
  12.     NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(downloadImage) object:nil];  
  13.     [operationQueue addOperation:op];  
  14. }  
  15.   
  16. - (void)downloadImage  
  17. {  
  18.     NSURL *imageUrl = [NSURL URLWithString:HEADIMAGE_URL];  
  19.     UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];  
  20.     self.imageview.image = image;  
  21. }  

不过这这样的设计,虽然是异步加载,但是没有缓存图片。重新加载时又要重新从网络读取图片,重复请求,实在不科学,所以可以考虑第一次请求时保存图片。

 

posted @   孙富有(iOS工程师)  阅读(7335)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
点击右上角即可分享
微信分享提示