Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does Core Data flush to disk?

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:

  • 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.

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)

like image 603
JRV Avatar asked Dec 04 '22 16:12

JRV


2 Answers

Stopping the simulator with the stop button in Xcode is probably the same as smashing your iPhone with a hammer (but preserving the SSD). Basically, your app and everything else just stops. There's no reasonable way to ensure that data is saved when that happens.

like image 66
JeremyP Avatar answered Dec 26 '22 20:12

JeremyP


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.

like image 39
Daniel Eggert Avatar answered Dec 26 '22 21:12

Daniel Eggert