I'm about to create a series of NSOperation
s 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
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.
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