Queue of NSOperations and handling application exit

…衆ロ難τιáo~ 提交于 2019-11-30 17:46:22

问题


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

They will all be sequential and run one at a time.

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.

Many thanks,

Mike


回答1:


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.

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.




回答2:


Your app will be forced to quit if it won't quit by itself for a specified time. So waiting for some data to come stumbling in from the internet might not be a good idea.

But you already gave yourself the answer. Just make the operations atomic by design. What I mean with this is that your operations should either complete the job (download + save of data) or you run it again on next startup. Make sure that all temp data of a job is rolled back if the did app quit before the job completed.



来源:https://stackoverflow.com/questions/1566230/queue-of-nsoperations-and-handling-application-exit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!