开发者

Correct approach for safely saving a Core Data managed object context on a background thread?

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 quitt开发者_运维知识库ing until all the save operation is complete.

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜