問題描述
我在我的應用程序中使用 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.
這篇關于Core Data 什么時候刷新到磁盤?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!