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];
    
}

 

转载于:https://www.cnblogs.com/ldnh/p/5281229.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值