前篇文章已经讲了GCD了,那么这两者有什么区别?
GCD VS NSOperation
“NSOperationQueue predates Grand Central Dispatch and on iOS it doesn’t use GCD to execute operations (this is different on Mac OS X). It uses regular background threads which have a little more overhead than GCD dispatch queues.
On the other hand, NSOperationQueue gives you a lot more control over how your operations are executed. You can define dependencies between individual operations for example, which isn’t possible with plain GCD queues. It is also possible to cancel operations that have been enqueued in an NSOperationQueue (as far as the operations support it). When you enqueue a block in a GCD dispatch queue, it will definitely be executed at some point.
To sum it up, NSOperationQueue can be more suitable for long-running operations that may need to be cancelled or have complex dependencies. GCD dispatch queues are better for short tasks that should have minimum performance and memory overhead.”
简单来说就是GCD偏底层点,性能好,依赖关系少,并发耗费资源少。
NSOperation可观察状态,性能也不错,处理事务更简单操作。
对于这两种都熟练运用的人来说,无所谓了,APP大多数事务这两者都能完美解决。至于代码用哪个这个取决于你的兴趣了。
下面详细说一下NSOperation
1 | @interface NSOperation : NSObject { |
NSBlockOperation
1 | - (void)print{ |
可以看出来,NSBlockOperation当任务是1的时候在main线程中执行,任务大于1的时候,其他的个自独自开了线程,而且互不影响。
依赖关系
1 | - (void)print{ |
从输出的信息可以看出来,block是同步执行的,虽然多任务是多线程,但是主线程还是在阻塞中,只有上一个所有 task 执行完的时候,才会执行下边的task。所以在这里依赖关系不那么重要了,注释掉运行结果也一样的。
NSInvocationOperation
1 | NSInvocationOperation 是NSOperation的子类,负责实现operation的SEL方法。 |
NSOperationQueue
1 | //添加操作 |
在子线程中耗时的操作完成了,那么该在主线程中更新UI
1 | #将上面的test5 改成下面的代码 |
关于NSOperationQueue的了解和使用我想到的基本就这么多场景,后期有其他的场景再补充。
预告:下期节目是NSThread的介绍和使用。
ps:广告时间
有问题可以发我邮箱讨论共同交流技术。
fgyong@yeah.net