美文网首页
NSOperation的使用注意点

NSOperation的使用注意点

作者: Sweet丶 | 来源:发表于2021-01-14 10:49 被阅读0次

iOS开发中我们可以通过使用NSOperation/NSOperationQueue来实现多线程,是基于GCD的一套封装。NSOperation是一个抽象类。使用的方式有三个:

  1. 使用子类 NSInvocationOperation
  2. 使用子类 NSBlockOperation
  3. 自定义继承自 NSOperation 的子类,通过实现内部相应的方法来封装操作。

具体的使用推荐查看iOS 多线程:『NSOperation、NSOperationQueue』详尽总结
我们在自定义一个operation时可以参考SDWebImage库里面的SDWebImageDownloaderOperation。接下来列举几个使用注意点:

An operation object is a single-shot object—that is, it executes its task once and cannot be used to execute it again. You typically execute operations by adding them to an operation queue (an instance of the NSOperationQueue class)`
操作对象是单快照对象,即它只执行一次任务,不能用于再次执行。通常通过将操作添加到操作队列(NSOperationQueue类的实例)来执行操作。

If you do not want to use an operation queue, you can execute an operation yourself by calling its start method directly from your code. Executing operations manually does put more of a burden on your code, because starting an operation that is not in the ready state triggers an exception.
如果不想使用操作队列,可以直接从代码中调用操作的start方法来执行操作。手动执行操作会给代码带来更大的负担,因为启动未处于就绪状态的操作会触发异常。

以上是官方的说明,经过测试代码总结如下:

  1. 将一个已完成或者正在执行的NSOperation添加到NSOperationQueue中会抛出异常。
  2. 将一个已经添加到queue中的NSOperation再次添加到queue中时会抛出异常。
  3. 直接对NSOperation调用start方法时,如果当前NSOperation未处于就绪状态(ready=NO)会抛出异常,通常是否就绪跟添加的NSOperation依赖有关系。
  4. 对设置了依赖关系的NSOperation之间,设置优先级不会起作用

NSOperation/NSOperationQueue
NSOperation

@property (readonly, getter=isCancelled) BOOL cancelled;
@property (readonly, getter=isExecuting) BOOL executing;
@property (readonly, getter=isFinished) BOOL finished;
- (void)addDependency:(NSOperation *)op;
- (void)removeDependency:(NSOperation *)op;
@property NSOperationQueuePriority queuePriority;

NSOperationQueue主要有两种queue:mainQueue和自己创建的queue

- (void)addOperation:(NSOperation *)op;
- (void)cancelAllOperations;
@property NSInteger maxConcurrentOperationCount;
@property (getter=isSuspended) BOOL suspended;

相对于GCD,NSOperation/NSOperationQueue的比较好用的功能:

  1. 可以使用KVO监听NSOperation的执行状态。
  2. 可以设置NSOperation的优先级,添加依赖。
  3. 可以扩展NSOperation的子类,重写main或者start方法来完成对应任务的封装。
  4. 可以设置NSOperationQueue最大并发数maxConcurrentOperationCount来控制串行还是并发,可以使队列中的任务暂停suspended添加到线程中。

在自定义NSOperation子类时需要注意的是:
1. start和main方法的区别

系统的NSOperation中的start方法中默认实现是会调用main方法,main方法结束,就意味着NSOperation执行完毕。
我们如果自定义的NSOperation,通过重写start方法,里面创建具体的任务,并且不要调用super去执行main,因为main函数执行完操作就结束了。
而start方法就算执行完毕,它的finish属性也不会变,因此你可以控制这个operation的生命周期,在具体的异步任务完成之后手动cancel掉这个operation。

相关文章

网友评论

      本文标题:NSOperation的使用注意点

      本文链接:https://www.haomeiwen.com/subject/wzwmaktx.html