如何使用NSOperation

先贴上一段官方介绍:

The NSOperation class is an abstract class you use to encapsulate the code and data associated with a single task. Because it is abstract, you do not use this class directly but instead subclass or use one of the system-defined subclasses (NSInvocationOperation or NSBlockOperation) to perform the actual task. 


翻译一下大概就是说NSOperation是一个抽象类,不能直接用,我们要用它的两个子类

(NSInvocationOperation or NSBlockOperation)来执行任务.


和NSOperation对应的有个线程队列(NSOperationQueue),下面结合讲一下一些基本用

法.


贴代码:



    - (void)viewDidLoad {[super viewDidLoad];

    // NSOperationQueue线程队列
    // 将多个子线程加到可执行队列中,让他们并发执行,来提高执行效率.但是数量不能太大,否则cpu压力会很大
    NSOperationQueue *queue  = [[NSOperationQueue alloc] init];
    // maxConcurrentOperationCount最大并发线程数,设为1就变成了串行,串行的时候遵循先进先出(addOperation:)
    queue.maxConcurrentOperationCount = 2;
    
    // NSOperation不能直接创建线程,需要用他的子类NSInvocationOperation or NSBlockOperation来创建
    // 方式一:NSInvocationOperation创建
    NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(OperationMethod1) object:nil];
    // 方式二:NSBlockOperation创建
    NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
        for (int i=0; i<4; i++) {
            NSLog(@"operation2: %d",i);
        }
    }];
    
    // 为Operation添加依赖
    // operation1添加依赖线程operation2,线程2执行完毕后线程一才能执行
    [operation1 addDependency:operation2];
    
    // 将线程加入队列
    [queue addOperation:operation1];
    [queue addOperation:operation2];

   
    
    // 将主线程'挂起',直到队列中的所有子线程执行完毕
    [queue waitUntilAllOperationsAreFinished];
    NSLog(@"回到主线程");
}

- (void)OperationMethod1
{
    for (int i=0; i<4; i++) {
        NSLog(@"operation1: %d",i);
    }
}

添加打印结果:

2015-12-31 18:47:30.050 NSOpration[3565:264172] operation2: 0
2015-12-31 18:47:30.050 NSOpration[3565:264172] operation2: 1
2015-12-31 18:47:30.051 NSOpration[3565:264172] operation2: 2
2015-12-31 18:47:30.051 NSOpration[3565:264172] operation2: 3
2015-12-31 18:47:30.052 NSOpration[3565:264177] operation1: 0
2015-12-31 18:47:30.052 NSOpration[3565:264177] operation1: 1
2015-12-31 18:47:30.052 NSOpration[3565:264177] operation1: 2
2015-12-31 18:47:30.052 NSOpration[3565:264177] operation1: 3
2015-12-31 18:47:30.053 NSOpration[3565:264071] 回到主线程

是不是得到了想要的结果.

NSOperationQueue不能直接设置并行队列还是串行队列,我们可以通过设置它的(maxConcurrentOperationCount)属性来设置队列中一次最大的并行线程数,如果设为1就可以达到串行的效果(注意:这是候的线程遵循I/O原则,谁先add进去谁先执行).如果需要比较复杂的队列运行情况就可以给线程(NSOperation)添加依赖的Operation,这样在依赖的线程没有执行完,该线程是不会执行的.同时NSOperationQueue还有一个将主线程挂起的方法,当调用-waitUnitlAlloperationArefinished方法时,主线程会挂起,直到queue中所有的operation执行完毕才能回到主线程继续执行.Ok,基本用法先说这么多..


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