iOS 多线程编程<十二、NSOperation线程间通信>

NSOperation线程间通信

具体代码如下:
//
//  ViewController.m
//  NSOperationDependency
//
//  Created by fe on 2016/10/20.
//  Copyright © 2016年 fe. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *girlImageView;
@property (nonatomic,strong) UIImage *image1 ;
@property (nonatomic,strong) UIImage *image2 ;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //1:创建队列
    NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
    
    
    //2:封装操作
    //2.1开启一条线程,下载图片一
    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
        
        NSURL *url = [NSURL URLWithString:@"http://image.cnwest.com/attachement/jpg/site1/20101022/001372d89ff00e2b26572e.jpg"];
        NSData *data = [NSData dataWithContentsOfURL:url];
        self.image1 = [UIImage imageWithData:data];
    }];
    //2.2开启一条线程,下载图片二
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        
        NSURL *url = [NSURL URLWithString:@"http://imgsrc.baidu.com/forum/w%3D580/sign=a73178ef3b01213fcf334ed464e736f8/7bb0c11b9d16fdfa85708ad8b68f8c5494ee7b43.jpg"];
        NSData *data = [NSData dataWithContentsOfURL:url];
        self.image2 = [UIImage imageWithData:data];
    }];
    
    //2.3开启一条线程,完成图片合成操作
    NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
        UIGraphicsBeginImageContext(CGSizeMake(300,600));
        [self.image1 drawInRect:CGRectMake(0, 0, 300, 300)];
        [self.image2 drawInRect:CGRectMake(0, 300, 300, 300)];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        //回到主线程刷新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            self.girlImageView.image = image;
        }];
    }];
    
    //3:因为合成图片需要在两张图片都下载完成之后进行合成,所以需要添加依赖
    [op3 addDependency:op2];
    [op3 addDependency:op1];
    
    //把任务添加到队列
    [operationQueue addOperation:op1];
    [operationQueue addOperation:op2];
    [operationQueue addOperation:op3];
}


@end
运行效果如下:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值