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

在iOS中,NSOperation的isConcurrent属性在iOS 4之后已不再决定是否并发执行。无论并发还是非并发,队列都会提供线程。start和main方法是关键:main方法完成即操作从队列移除,可能导致代理失效;而start方法允许控制操作生命周期并在完成后手动cancel。

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即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值