4

The Apple "Concurrency with Core Data" documentation states the following when discussing using core data with background threads.

Saving in a Background Thread is Error-prone

Asynchronous queues and threads do not prevent an application from quitting. (Specifically, all NSThread-based threads are “detached”—see the documentation for pthread for complete details—and a process runs only until all not-detached threads have exited.)

and in particular:

If you need to save on a background thread, you must write additional code such that the main thread prevents the application from quitting until all the save operation is complete.

What is the recommended approach for achieving this inside an IOS application?

2 Answers 2

5

In the app delegates applicationWillTerminate and related methods, you need to check if any background threads have unsaved changes and save them before allowing the app to terminate or go into the background.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 Right, but be sure to note that "related methods" includes applicationDidEnterBackground -- the app can go into the background and then become suspended & terminate without any further notification.
Thanks. I haven't done a lot with threads inside the IOS framework, do you have either have some example code or could you point me in the direction of some documentation on how to access and check a thread from unsaved changes from inside the app delegate class.
All depends how you've implemented the threading really. For example, if you're using an NSOperationQueue, the waitUntilAllOperationsAreFinished could be useful.
0

I recommend taking a look at using Magical Record (https://github.com/magicalpanda/MagicalRecord/). It greatly simplifies dealing with core data on background threads. I recently found this and used it for a project. We've now undertaken a maintenance effort to update a variety of existing apps to use the new Magical Record Core Data wrapper. It has saved us tons of time and frustration in the few weeks we have been using it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.