iOS 多线程编程

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
运行效果如下:
iOS 多线程编程_第1张图片

你可能感兴趣的:(iOS开发)