核心数据何时刷新到磁盘? [英] When does Core Data flush to disk?

查看:90
本文介绍了核心数据何时刷新到磁盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中使用了Core Data,并发现了模拟器的一些奇怪行为:当我向应用程序中的Core Data添加一些数据并使用XCode中的停止按钮退出模拟器时(或仅按Cmd-Q ),下次我下次启动模拟器时,数据不会存储在数据库中。经过一些测试,我发现数据已存储到磁盘:

I use Core Data in my application, and discovered some odd behavior of the simulator: When I add some data to Core Data in my app and quits the simulator using the "stop" button in XCode (or just press Cmd-Q) immediately, the data is not stored in the database the next time I start the simulator. After some testing, I found out, that the data is stored to disk:


  • 如果按下主屏幕按钮,则立即。 (如果退出速度非常快,几乎可以- 可以在存储数据之前退出应用程序。)

  • 如果我让应用程序运行了一段时间(至少添加数据后大约20秒)。

  • immediately if I press the home button. (Almost - it is possible to quit the application before data is stored if quitting very fast.)
  • If I let the application run for some time (at least about 20 seconds) after adding data.

调用[NSManagedObjectContext save:]无济于事。行为是相同的。

It does not help to call [NSManagedObjectContext save:]. The behavior is the same.

所以我的问题是:这种行为的原因是什么?有什么方法可以在退出之前强制刷新到磁盘吗?并且在设备上运行时是否存在以这种方式丢失数据的风险(个人而言,除了强制关闭外,我看不到任何东西,但奇怪的行为使我有些困扰)

So my question is: What is the reason for this kind of behavior? Are there any way to force flushing to disk before quitting? And are there any risk that I can loose data this way when running on a device (personally, I do not see any, except a force close, but the odd behavior bothers me a bit)

推荐答案

您可能正在使用嵌套上下文。如果您的上下文具有父上下文,则调用 -save:只会保存到该上下文,而不是文件系统。

You're probably using nested context's. If your context has a parent context, calling -save: will just save to that context, not to the file system.

嵌套上下文(通常)用于安全地在后台队列中使用上下文,并允许保存前景上下文而不必招致保存到文件系统的开销。保存到文件系统将在后台队列中进行,而不会阻塞主线程。

Nested context are (usually) used to safely use a context on a background queue, and allowing a foreground context to save without having to incur the overhead of saving to the file system. The save to the file system will happen on a background queue and not block the main thread.

这篇关于核心数据何时刷新到磁盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆