[iOS]NSOperation的start与main,并发与非并发。

NSOperation有一个属性,isConcurrent.

Operation queues usually provide the threads used to run their operations. In OS X v10.6 and later, operation queues use the libdispatch library (also known as Grand Central Dispatch) to initiate the execution of their operations. As a result, operations are always executed on a separate thread, regardless of whether they are designated as concurrent or non-concurrent operations. In OS X v10.5, however, operations are executed on separate threads only if their isConcurrent method returns NO. If that method returns YES, the operation object is expected to create its own thread (or start some asynchronous operation); the queue does not provide a thread for it.

在ios4以前,只有非并发的情况下,队列会为operation开启一个线程来执行。如果是并发的情况,operation需要自己创建一个线程来执行。所以说,NSoperation的并发和非并发不是传统意义上的串行和并行。

但是在ios4以后,不管是并发还是非并发,队列都会为operation提供一个线程来执行。所以isConcurrent这个变量也就没有用处了。


但是,这里还设涉及到了两个方法,start和main.

按照官方文档所说,如果是非并发就使用main,并发就使用start。

那现在并发和非并发已经没有区别了,start和main的区别在哪里呢?

main方法的话,如果main方法执行完毕,那么整个operation就会从队列中被移除。如果你是一个自定义的operation并且它是某些类的代理,这些类恰好有异步方法,这是就会找不到代理导致程序出错了。

然而start方法就算执行完毕,它的finish属性也不会变,因此你可以控制这个operation的生命周期了。

然后在任务完成之后手动cancel掉这个operation即可。

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