ios UIImageView异步加载网络图片

时间:2023-03-08 20:03:51
ios UIImageView异步加载网络图片

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

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

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

方法2:使用NSOperationQueue异步加载

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

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