Search code examples
iosobjective-cios5core-dataios6

CoreData - when do I save?


I understand how to use CoreData, but I'm confused when it's best to save the data. When they press the home button? On every interaction in case the app crashes?


Solution

  • The reason why saving data is a separate call is so that you can batch multiple smaller changes that comprise a larger operation and save all at once, rather than saving at each step along the way.

    You should save the data after each atomic operation, and never have committed data sitting only in memory for any significant period of time.

    Each time the user commits a change to the data, they will expect the data to be there the next time they run the app, so it's your job to make sure it's there.

    After your user submits a change to the data, your app is likely going to be waiting for the user do something else anyway, so save the data while the user decides what to do next.

    If you wait to save data in the applicationDidEnterBackground, there is no guarantee that it will ever be called.

    Obviously, not all data is critical, for example, data that a user has entered on a form, but hasn't submitted, is not critical. However, any submitted data is critical.