iOS NSOperation使用

//
//  NSOperationViewController.m
//  DemoTest
//
//  Created by biyabi on 15/8/18.
//  Copyright (c) 2015年 test. All rights reserved.
//
#import "NSOperationViewController.h"
#import "HeadFile.h"
#define imageURL @"http://images.cnitblog.com/blog/381483/201408/221614287532594.png"
#define imageURLCache @"http://c11.eoemarket.com/upload/2011/1213/apps/64183/screenshots/95489.png"
#define imageURLEnd @"http://img1.ali213.net/picfile/News/2012/06/25/am/he24.jpg"
@interface NSOperationViewController ()
@property (nonatomic, strong) UIImageView *imageView;
@end
@implementation NSOperationViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.title = @"NSOperation";
    [self initUI];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    
    //方式一:
    //    NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(threadRun:) object:imageURL];
    //    [queue addOperation:operation];
    
    //方式二:有依赖关系的 就是要线程A和线程B先执行完毕,才能执行线程C
    __weak typeof(self) weakself = self;
    NSBlockOperation *operationA = [NSBlockOperation blockOperationWithBlock:^{
        [weakself threadRun:imageURL];
    }];
    
    NSBlockOperation *operationB = [NSBlockOperation blockOperationWithBlock:^{
        [weakself threadRun:imageURLCache];
    }];
    
    NSBlockOperation *operationC = [NSBlockOperation blockOperationWithBlock:^{
        [weakself threadRun:imageURLEnd];
    }];
    
    [operationA addDependency:operationB];
    [operationA addDependency:operationC];
    
    [queue addOperation:operationA];
    [queue addOperation:operationB];
    [queue addOperation:operationC];
    
}
- (void)threadRun:(NSString *)url{
    NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:url]];
    UIImage *image = [[UIImage alloc]initWithData:data];
    if (!data) {
        return;
    }
    [self performSelectorOnMainThread:@selector(updataImage:) withObject:image waitUntilDone:YES];
}
- (void)updataImage:(UIImage *)image{
    [self.imageView setImage:image];
}
- (void)initUI{
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth-200)/2, (ScreenHeight-200)/2, 200, 200)];
    [self.view addSubview:self.imageView];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
@end

你可能感兴趣的:(多线程,ios,NSOperation)