线程NSOperationQueue

1.NSOperationQueue下载图片

 1 #import "ViewController.h"
 2 #import "ImageOperation.h"
 3 
 4 @interface ViewController ()
 5 {
 6     NSOperationQueue *_queue;
 7 }
 8 @end
 9 
10 @implementation ViewController
11 
12 - (void)viewDidLoad {
13     [super viewDidLoad];
14     // Do any additional setup after loading the view, typically from a nib.
15     //图片视图
16     UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
17     [self.view addSubview:imageView];
18     
19     //创建线程下载
20     _queue = [[NSOperationQueue alloc] init];
21     ImageOperation *op = [[ImageOperation alloc] init];
22     op.urlString = @"http://g.hiphotos.baidu.com/image/pic/item/4034970a304e251fb3145e6ca586c9177e3e5346.jpg";
23     op.imageView = imageView;
24     
25     [_queue addOperation:op];
26 }
27 
28 - (void)didReceiveMemoryWarning {
29     [super didReceiveMemoryWarning];
30     // Dispose of any resources that can be recreated.
31 }
32 
33 @end
View Code

2.封装ImageOperation

 1 #import "ImageOperation.h"
 2 
 3 @implementation ImageOperation
 4 
 5 //线程执行体方法
 6 -(void)main
 7 {
 8     //下载图片
 9     NSURL *url = [NSURL URLWithString:self.urlString];
10     NSData *data = [NSData dataWithContentsOfURL:url];
11 
12   //在主线程执行方法
13     [self performSelectorOnMainThread:@selector(refreshUI:) withObject:data waitUntilDone:YES];
14 }
15 
16 -(void)refreshUI:(NSData *)data
17 {
18     self.imageView.image = [UIImage imageWithData:data];
19 }
20 
21 @end
View Code
原文地址:https://www.cnblogs.com/liaods/p/4788874.html