NSoperation线程通信
全局变量
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic, strong) NSOperationQueue * queue;
懒加载
- (NSOperationQueue *)queue {
if (!_queue) {
_queue = [[NSOperationQueue alloc] init];
}
return _queue;
}
事件的响应方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
__block UIImage * image1;
//创建操作1
NSBlockOperation * download1 = [NSBlockOperation blockOperationWithBlock:^{
NSURL * url = [NSURL URLWithString:@"http://g.hiphotos.baidu.com/lvpics/w=1000/sign=82800ad878cb0a4685228f395b53f724/96dda144ad3459823cc40db00ff431adcbef8442.jpg"];
NSData * data = [NSData dataWithContentsOfURL:url];
image1 = [UIImage imageWithData:data];
NSLog(@"download1- %@",[NSThread currentThread]);
}];
__block UIImage * image2;
//创建操作2
NSBlockOperation * download2 = [NSBlockOperation blockOperationWithBlock:^{
NSURL * url = [NSURL URLWithString:@"http://f.hiphotos.baidu.com/lvpics/h=800/sign=08f9c974e21190ef1efb9fdffe1a9df7/c8177f3e6709c93dfd03176e9a3df8dcd00054b1.jpg"];
NSData * data = [NSData dataWithContentsOfURL:url];
image2 = [UIImage imageWithData:data];
NSLog(@"download2- %@",[NSThread currentThread]);
}];
//创建操作3(用于合并图片)
NSBlockOperation * combine = [NSBlockOperation blockOperationWithBlock:^{
//创建位图上下文
UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), NO, 1);
//设置显示的位置
[image1 drawInRect:CGRectMake(0, 0, 200, 100)];
[image2 drawInRect:CGRectMake(0, 100, 200, 100)];
//获取当前图片上下文
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSLog(@"combine- %@",[NSThread currentThread]);
//返回主线程更新UI
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.imageView.image = image;
NSLog(@"main - %@",[NSThread currentThread]);
}];
}];
//设置操作的依赖关系
[combine addDependency:download1];
[combine addDependency:download2];
//向全局队列添加操作
[self.queue addOperations:@[download1,download2,combine] waitUntilFinished:YES];
}
您的资助是我最大的动力!
金额随意,欢迎来赏!