• 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. }  

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

  • 相关阅读:
    在dubbo的一端,看Netty处理数据包,揭网络传输原理
    解惑:什么叫模型?
    拜托!不要再问我是否了解多线程了好吗
    微软职位内部推荐-Senior SW Engineer for Application Ecosystem
    微软职位内部推荐-Senior Software Engineer
    微软职位内部推荐-Senior Software Engineer_Azure
    微软职位内部推荐-Software Engineer II
    微软职位内部推荐-Senior Software Engineer
    微软职位内部推荐-Software Engineer II
    微软职位内部推荐-Senior Software Engineer
  • 原文地址:https://www.cnblogs.com/sunfuyou/p/6285655.html
Copyright © 2020-2023  润新知