Objective c - Core Data saving approach

2019-03-04 07:29发布

问题:

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 A is NSManagedObject subclass.
During app life cycle I do:

App launched
...
Create an instance of class A
...
Change some properties of A instance
...
App go to background
...
App becomes active again
...
Change some more properties of A instance
...
App terminates

When do I need to call [context save:] ??
Do I call it after every change in A instance? Or maybe I call it only when app go to background?
Should I call it after creation or deletion of any A instance?

回答1:

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



回答2:

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.



回答3:

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