-1

I would like to know how to use multithreading in iOS. I am aware of GCD and NSOperationQueue, but I am not sure how to use them properly.

  1. When should I use GCD/NSOperationQueue?
  2. How do I cancel a queue if the view for the results are no longer in view? (i.e. send a request for something, but user then decides to hit the back button to go to another view, which means I no longer require that "something")

Any examples will be greatly appreciated.

Thank you.

4

2 回答 2

1

可能值得一提的是,一旦操作开始(GCD 块或 NSOperation),您只能在操作本身内置取消能力的情况下取消它。例如, NSOperation 有一个-cancel方法,但只有当您的操作定期检查-isCanceled操作内部的标志,然后如果它看到操作已被取消,则提前返回。从文档中-[NSOperation cancel]

此方法不会强制您的操作代码停止。相反,它会更新对象的内部标志以反映状态的变化。如果操作已经执行完毕,则此方法无效。取消当前在操作队列中但尚未执行的操作可以比平时更快地从队列中删除操作。

同样,GCD 块可以检查一些共享标志并提前返回,但这些机制都不能强制取消操作。这样做的原因是,如果您能够强制取消操作,它将没有机会自行清理,因此在任务期间分配的任何内存都会泄漏。

绕过此限制的另一种常见方法是将您的任务划分为更多较小的操作,以便完成单个操作的时间小到可以忽略不计。这使您能够在整个队列级别暂停/取消队列/NSOperationQueue,并大致达到预期的效果。

于 2013-06-14T19:33:21.647 回答
0

Just going through the Apple Docs you can find the methods setSuspended: and cancelAllOperations. This can be used to achieve what you are asking for.

于 2013-06-13T08:59:05.873 回答