码迷,mamicode.com
首页 > 移动开发 > 详细

iOS 多线程(NSOperationQueue)

时间:2015-09-11 14:23:09      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

1.就基本使用

NSInvocationOperation

//1.创建操作对象,封装需要执行的任务
    NSInvocationOperation * operation =[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download) object:nil];
    
    //2.执行操作(默认情况下,如果操作没有放到队列queue中,都是同步执行)
    [operation start];

- (void)download{
    NSLog(@"--------下载图片-----%@",[NSThread currentThread]);
}

 

NSBlockOperation

 //1.封装操作
    NSBlockOperation * operation=[NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"--------下载图片-----%@",[NSThread currentThread]);
    }];
    
    [operation addExecutionBlock:^{
         NSLog(@"--------下载图片1-----%@",[NSThread currentThread]);
    }];
    [operation addExecutionBlock:^{
         NSLog(@"--------下载图片2-----%@",[NSThread currentThread]);
    }];
    

    //2.执行操作
    [operation start];
    
    //注意:只要NSBlockOperation封装的操作数>1,就会异步执行操作

 

 NSOperationQueue 操作队列

 //创建操作队列
    NSOperationQueue * queue =[[NSOperationQueue alloc]init];
    NSInvocationOperation *operation1 =[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download) object:nil];
    NSInvocationOperation * operation2 =[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(run) object:nil];
    
    NSBlockOperation * operation3 =[NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"--------下载图片2-----%@",[NSThread currentThread]);
        
    }];
    
    [operation3 addExecutionBlock:^{
        NSLog(@"--------run2-----%@",[NSThread currentThread]);

    }];
    
    
    [queue addOperation:operation1];
    [queue addOperation:operation2];
    [queue addOperation:operation3];
 //将操作放在队列里才能异步操作

 

*设置最大并发数

- (void)setMaxConcurrentOperationCount:(NSInteger )cnt;

 

*设置依赖

[opetationB  addDependency:operationA];//操作B依赖于操作A       A执行完才会执行B

 

iOS 多线程(NSOperationQueue)

标签:

原文地址:http://www.cnblogs.com/wangbinbin/p/4800562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!