zoukankan      html  css  js  c++  java
  • 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. }  

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

  • 相关阅读:
    第06组 每周小结 (1/3)
    第06组 Beta冲刺 总结
    第06组 Beta冲刺(5/5)
    爬虫第六次作业
    第06组 Beta冲刺 (4/5)
    第06组 Beta冲刺 (3/5)
    第06组 Beta冲刺 (2/5)
    《机器学习》第二次作业——第四章学习记录和心得
    软工实践个人总结
    第09组 每周小结 (3/3)
  • 原文地址:https://www.cnblogs.com/sunfuyou/p/6285655.html
Copyright © 2011-2022 走看看