在后台线程上安全保存核心数据托管对象上下文的正确方法?
Apple“与核心数据的并发”文档在讨论将核心数据与后台线程一起使用时声明了以下内容。
在后台线程中保存很容易出错
异步队列和线程不会阻止应用程序 戒烟。 (具体来说,所有基于 NSThread 的线程都是“分离的”——参见 有关完整详细信息的 pthread 文档以及进程的运行 仅直到所有未分离的线程退出为止。)
,特别是:
如果需要在后台线程上保存,则必须编写额外的代码,以便主线程阻止应用程序退出,直到所有保存操作完成。
在 IOS 应用程序中实现此目的的推荐方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在应用程序委托
applicationWillTerminate
和相关方法中,您需要检查是否有任何后台线程有未保存的更改,并在允许应用程序终止或进入后台之前保存它们。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.我建议看看使用 Magical Record (https://github.com/magicalpanda/MagicalRecord/ )。它极大地简化了后台线程上核心数据的处理。我最近发现了这个并将其用于一个项目。我们现在已经进行了维护工作,更新各种现有应用程序以使用新的 Magical Record 核心数据包装器。在我们使用它的几周内,它为我们节省了大量的时间和挫败感。
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.