一:简介

1.NSOperation的作用:

配合NSOperation与NSOperationQueue也可以实现多线程。

2.NSOperation与NSOperationQueue实现多线程的步骤:

  2.1现将需要执行的操作封装到NSOperation对象中

  2.2然后将NSOperation添加到NSOperationQueue中

  2.3系统会自动将NSOPerationQueue中的NSOPeration取出来

二:NSOPeration的子类

1.NSOPeration是个抽象类,并不具备封装操作的能力,必须使用他的子类。

 

2.使用NSOPeration子类的方式有三种:

2.1NSInvocationOpertation

2.2NSBlockOperating

2.3自定义子类继承NSOperation,实现内部相应方法

 

三:NSOPerationQueue

1.NSOperationQueue 的类型:

 1.1主队列,通过 [NSOperationQueue mainQueue];可以获得。

 1.2其他队列:串行队列,并发队列。 通过 [[NSOperationQueue alloc ] init];可以获得。

2.使用:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
   NSOperationQueue *opQ = [[NSOperationQueue alloc ] init];
    
    NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run1) object:nil];
    
    NSInvocationOperation *op2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run2) object:nil];
    
    [opQ addOperation:op1];// 会在内部调用[op1 start]这个方法并放入子线程内
    
    [opQ addOperation:op2];
}
- (void)run1{
    NSLog(@"1 ------ %@",[NSThread currentThread]);
}
- (void)run2{
    NSLog(@"2  ------ %@",[NSThread currentThread]);
}

3.自定义Operation

3.1使用场景:当操作比较复杂时,就可以自定义一个NSOperation,然后将复杂的操作放在自定义operation里。

3.2实现:

   3.2.1需要在自定义Operation中重写main函数:

    如:

- (void)main
{
    NSLog(@"%@-----------------自定义Operation",[NSThread currentThread]);
}

  3.2.2创建自定义Operation 添加到队列里去:  

    ZZNSOpertation *op3 = [[ZZNSOpertation alloc] init];

    [opQ addOperation:op3];

  3.2.3打印结果:

2016-01-19 17:43:39.941 NSPerationQueue[16438:1477860] <NSThread: 0x7ff00a60d600>{number = 4, name = (null)}-----------------自定义Operation