Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to place the "Core Data Stack" in a Cocoa/Cocoa Touch application

In the iPhone Core Data Template, Apple places the Core Data Stack in the App Delegate.

My initial inclination however is to move this code into it's own class whose responsibility is to handle the management of the Core Data Stack.

Do you typically encapsulate this functionality within its own class or do you leave it in the App Delegate?

like image 605
Corey Floyd Avatar asked Aug 12 '09 17:08

Corey Floyd


People also ask

What is Core Data stack?

As I mentioned earlier, the Core Data stack is the heart of Core Data. It's a collection of objects that make Core Data tick. The key objects of the stack are the managed object model, the persistent store coordinator, and one or more managed object contexts.

What is Persistentcontainer in Core Data?

NSPersistentContainer simplifies the creation and management of the Core Data stack by handling the creation of the managed object model ( NSManagedObjectModel ), persistent store coordinator ( NSPersistentStoreCoordinator ), and the managed object context ( NSManagedObjectContext ).


1 Answers

Summary: There is no need to create a singleton to manage the Core Data stack; indeed doing so is likely to be counter-productive.

The Core Data stack happens to be created by the application delegate. Importantly, however, as all the examples show, the stack (principally the managed object context) is not retrieved directly from the stack(*). Instead the context is passed to the first view controller, and from them on a context or a managed object is passed from one view controller to the next (as described in Accessing the Core Data Stack). This follows the basic pattern for iPhone all applications: you pass data or a model controller from one view controller to the next.

The typical role of the singleton as described here is as a model controller. With Core Data, the managed object context is already a model controller. It also gives you the ability to access other parts of the stack if needs be. Moreover, in some situations (as described in the documentation) you might want to use a different context to perform a discrete set of actions. The appropriate unit of currency for a view controller is therefore usually a managed object context, otherwise a managed object. Using and passing a singleton object that manages a stack (and from which you retrieve a context) typically at best introduces a needless level of indirection, and at worst introduces unnecessary application rigidity.

(*) No example retrieves the context using:

[[UIApplication delegate] managedObjectContext]; 
like image 177
mmalc Avatar answered Sep 28 '22 14:09

mmalc