Reputation: 149
I have a singleton data controller to hold an array of objects. See for example bananas question for my solution: singelton dataController banansArray
Now I want to save the array of bananas to persistant state. This core data tutorial: core data - store images have given me a good general understanding of Core Data and I was able to include it in my application before changing my data Controller to singleton.
Now what is best?
Do I need to move the generated Core Data stack within the application delegate to the singletonDataController that manage the bananas array? Or do I have to set the context of the singleton in the application delegate as you do in the generated Master-View controller with Core Data template?
In that case how do I set the context in the appDelegate?
This does not work (it workes for the masterView in template) in the AppDelegate application didFinishLaunchingWithOptions:
DataControllerSingleton *dataController;
dataController.managedObjectContext = self.managedObjectContext;
In beerDataModel example provided the ManagedObjectCode is:
if (_mainContext == nil) {
_mainContext = [[NSManagedObjectContext alloc] init];
_mainContext.persistentStoreCoordinator = [self persistentStoreCoordinator];
}
Upvotes: 0
Views: 2023
Reputation: 33428
Based on your question, I think it's a personal choice. For example, within my project I prefer to maintain a singleton class for managing the Core Data stack and use it throughout the application. I prefer to leave the app delegate clean.
Anyway, now if you use Core Data the old singleton, the one that manages the arrays of objects, is not useful anymore. With Core Data you have a graph of objects that can be grabbed from a persistent store (for example). Obviously you need to design your model correctly (entities, relationships, etc.). In your case, for example, a Banana
entity with the correct attributes is the right choice.
To see in action a singleton class take a look at BeerDataModel.h/.m
by @BenSheirman. This is a very good approach to follow. It can be used like the following.
NSManagedObjectContext *mainContext = [[BeersDataModel sharedDataModel] mainContext];
P.S. Change BeersDataModel
in BananasDataModel
or what name you prefer.
Upvotes: 2