NSOperations的队列和处理应用程序退出 [英] Queue of NSOperations and handling application exit

查看:129
本文介绍了NSOperations的队列和处理应用程序退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建一系列 NSOperation ,并将它们在队列中运行。

I'm about to create a series of NSOperations and run them in a queue.

这些操作将从网页获取数据并创建和保存核心数据托管对象。

These operations will fetch data from the web and create and save core data managed objects.

如何处理应用程序退出的情况?由于操作在分离的线程中运行,我如何使主线程等待直到当前操作安全退出?在某些情况下,我很高兴线程(操作)在完成之前退出,因为在进一步的应用程序启动时,作业将继续并从中断的位置继续。

How do I handle the situation where the application exits? As the operations run in detached threads, how can I make the main thread wait until the current operation is "safe" to quit? There are situations where I'm happy for the threads (operations) to exit before they are complete as on further app launches the job will continue and pick up where it left off.

非常感谢,

Mike

推荐答案

他们在适当的安全时间(在开始,操作的一个阶段完成之后等等)检查它们的 isCancelled 属性,并在那时释放。在 applicationWillTerminate 中,向您的操作队列发送一个 -cancelAllOperations 消息, -waitUntilAllOperationsAreFinished 消息。这将阻塞,直到队列中的所有操作都完成。如果所有的操作都正确处理 isCancelled ,这不应该减慢你的应用程序退出。

Design your operations so that they check their isCancelled property at appropriate safe times (at start, after one stage of the operation has completed, etc.) and bail out at that point. In applicationWillTerminate, send your operation queue a -cancelAllOperations message, and follow that up with a -waitUntilAllOperationsAreFinished message. This will block until all operations in the queue have completed. This shouldn't slow your application exit much if all of the operations handle isCancelled properly.

out是当从 applicationWillTerminate 调用 -waitUntilAllOperationsAreFinished 时,将在主线程上阻塞的事实。如果你的任何操作在主线程上执行一个选择器,你的应用程序将冻结在那一点。

One thing to watch out for is the fact that -waitUntilAllOperationsAreFinished, when called from applicationWillTerminate, will block on the main thread. If any of your operations perform a selector on the main thread, your application will freeze at that point.

这篇关于NSOperations的队列和处理应用程序退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆