二、ios中的NSOperation

一、简介:
 NSOperation是基于GCD之上的更高一层封装,NSOperation需要配合NSOperationQueue来实现多线程。
 NSOperation是一个抽象类,它不能直接使用,所以你必须使用NSOperation子类。可以使用系统提供的NSBlockOperation和NSInvocationOperation,也可以自定义Operation.
NSBlockOperation——使用这个类来用一个或多个block初始化操作。操作本身可以包含多个块。当所有block被执行操作将被视为完成。NSInvocationOperation——使用这个类来初始化一个操作,它包括指定对象的调用selector。
 NSOperation可以自己独立执行(直接调用[operation start]),也可以放到NSOperationQueue里面执行,这两种情况下是否并发执行是不同的。一旦NSOperation被add到Queue里面必定是并发执行,可以通过设置NSOperationQueue的maxConcurrentOperationCount设置最大并发数,如果设置为1,那么这个Queue就是串行队列了。Queue会为每一个add到队列里面的operation创建一个线程来运行其start函数, 这样每个start都分布在不同的线程里面来实现operation们的并发执行.我们这边所说的并发都是指NSOperation之间的并发(多个operation同时执行), 如果maxConcurrentOperationCount设置为1或者把operation放到[NSOperationQueue mainQueue]里面执行, 那它们只会顺序(Serial)执行, 当然就不可能并发了.

二、NSOperation的优势:
  1.通过NSOperation类里的方法addDependency(op:NSOperation)支持依赖。当你需要开始一个依赖于其它操作执行的操作,你会需要NSOperation。
 2.可以通过Queue的maxConcurrentOperationCount设置最大并发数
  3.对于任何给定的队列,你可以取消一个特定的或所有的操作。操作可以在被添加到队列后被取消。取消是通过调用NSOperation类里的方法cancel()。当你取消任何操作的时候,我们有三个场景,其中一个会发生:
你的操作已经完成。在这种情况下,取消方法没有效果。
你的操作已经被执行。在这种情况下,系统不会强制操作代码停止,而是属性cancelled被置为true。
你的操作仍在队列中等待。在这种情况下,你的操作将不会被执行。
4.NSOperation有3个有用的布尔属性,finished、 cancelled和ready。一旦操作执行完成,finisher将被置为true。一旦操作被取消,cancelled将被置为true。一旦准备即将被执行,ready将被置为true。

三、NSOperation的一些其他操作
  1.取消队列NSOperationQueue的所有操作,NSOperationQueue对象方法
    - (void)cancelAllOperations
  2.取消NSOperation的某个操作,NSOperation对象方法
    - (void)cancel
  3.使队列暂停或继续
    // 暂停队列
    [queue setSuspended:YES];
  4.判断队列是否暂停
    - (BOOL)isSuspended
暂停和取消不是立刻取消当前操作,而是等当前的操作执行完之后不再进行新的操作。

四、自定义NSOperation
1.NSOperation默认是非并发执行的,也就是说如果你把operation放到某个线程去执行,它会一直block住该线程,直到operation finished. 对于非并发的operation你只需要继承NSOperation,然后重写main()方法就妥妥滴了。
   比如我们用非并发的operation来实现一个下载需求:
     @implementation YourOperation 
      - (void)main 
      {
        @autoreleasepool {
          if (self.isCancelled) return;
          NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageURL];
          if (self.isCancelled) { imageData = nil; return; }
          if (imageData) {
              UIImage *downloadedImage = [UIImage imageWithData:imageData];
          }
          imageData = nil;
          if (self.isCancelled) return;
          [self.delegate performSelectorOnMainThread:@selector(imageDownloaderDidFinish:)                                                                  
                                        withObject:downloadedImage
                                     waitUntilDone:NO];
          }
      }
      @end

  由于NSOperation是可以cancel的,所以你需要在operation程序内部执行过程中判断当前operation是否已经cancel了(isCancelled)。如果已经被cancel那就不往下执行了。当你在外面调用[operation cancel]后, isCancelled会被置为YES.
  NSOperation有三个状态量isCancelled,isExecuting和isFinished.main函数执行完成后,isExecuting会被置为NO,而isFinished则被置为YES.

  2.NSOperation实现并发:
    1).重写isConcurrent函数, 返回YES, 这个告诉系统各单位注意了我这个operation是要并发的.
    2).重写start()函数.
    3).重写isExecuting和isFinished函数
  为什么在并发情况下需要自己来设定isExecuting和isFinished这两个状态量呢?因为在并发情况下系统不知道operation什么时候finished,opetaion里面的task一般来说都是异步执行的,也就是start函数返回了operation不一定就是finish了。
  这个你自己来控制, 你什么时候将isFinished置为YES(发送相应的KVO消息), operation就什么时候完成了.

  - (void) start {
    @synchronized(self){
        if (self.isCancelled){
            self.finished = YES;
            [self reset];
            return;
        }
        NSURLSession *session = self.session;
        if (!session){
            NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
            sessionConfig.timeoutIntervalForRequest = 15;
            self.session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
            session = self.session;
        }
        [self downLoadWithURL:self.url];
        self.executing = YES;
        self.thread = [NSThread currentThread];
    }
}
   - (BOOL) isConcurrent {
      return YES;
  }
  - (BOOL) isExecuting {
      return  _executing;
  }
  - (BOOL) isFinished {
      return  _finished;
  }
  - (void) setExecuting:(BOOL)executing{
      [self willChangeValueForKey:@"isExecuting"];
      _executing = executing;
      [self didChangeValueForKey:@"isExecuting"];
  }
  - (void) setFinished:(BOOL)finished {
      [self willChangeValueForKey:@"isFinished"];
      _finished = finished;
      [self didChangeValueForKey:@"isFinished"];
  }
需要注意的是:
  1)operation的executing和finished状态量需要用willChangeValueForKey/didChangeValueForKey来触发KVO消息.
  2)在调用完NSURLSession之后start函数就返回了, 后面就坐等NSURLSession的回调了.
  3)在NSURLSession的didCompleteWithError会调里面设置operation的finish状态,告诉系统operation执行完毕了。

  参考文献:
  http://www.cocoachina.com/ios/20151201/14517.html
  http://www.cocoachina.com/ios/20160201/15179.html
  http://www.cocoachina.com/ios/20170707/19769.html

你可能感兴趣的:(二、ios中的NSOperation)