Objective c - Core Data saving approach

前端 未结 3 1244
伪装坚强ぢ
伪装坚强ぢ 2021-01-28 12:38

I have some NSManagedObject subclass in my app, and I\'m trying to understand when and how to save changes.
I will try to explain myself, for example class

相关标签:
3条回答
  • 2021-01-28 13:04

    A nice approach is place UIManagedDocument in your AppDelegate. Then you can call [context save] whenever some change occurs in the app (like a crash). The order I like to follow is something like:

    1. Create UIManagedDocument object (in application did load or wherever) and assign it to a property
    2. Setup the document (check whether it exist on disk or is already open, etc.. and respond accordingly)
    3. Pass the UIManagedObjectContext to the initial UIViewController in your app (from there you can pass the context to other view controllers)

    UIManaged document will save the context for you.

    Take a look at the UIManagedDocument documentation to configure persistent store options (you send an NSDictionary of options to your UIManagedDocument instance, see the first example through the link below).

    UIManagedDocument documentation: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIManagedDocument_Class/Reference/Reference.html

    Also see the CoreData lecture and demo (lectures 13 and 14) of the iPhone and iPad application development course with Paul Hegarty available free on iTunesU (Fall 2011).

    0 讨论(0)
  • 2021-01-28 13:12

    The data will not be saved to the persistent store until you call save. So, it depends on what you want in your app. If you want it to be able to recover the last value it ever had, then you should save after each modification.

    Easy change is to just save after making modifications.

    You could do something a bit more fancy, like only save after some set amount of time, so many changes are grouped together... and catch any event that will put your app in the background and then save...

    But, that's what UIManagedDocument does automatically for you, so you could just use that instead.

    0 讨论(0)
  • 2021-01-28 13:26

    Depending on the amount of changes that you make and the volume of data that needs to be saved with each change, yo can choose to save a little or a lot. If you are just saving a string or a number or a bool, then go ahead and call save: on your context as soon as the changes were made.

    If it is a lot of data, you may want to coalasce your changes and then save it on a background queue so that you are not blocking the main queue. This way you are not waiting to go to the background to perform your saves.

    Tim

    0 讨论(0)
提交回复
热议问题