Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data singleton manager?

What technical reasons are there not to make a singleton class to manage my Core Data? I'm trying to make a decision now, if I should strip out all of the boilerplate core data code and re-implement it in a singleton.

like image 236
Moshe Avatar asked Jun 13 '11 20:06

Moshe


2 Answers

The boilerplate code in the application delegate in the Xcode templates is functionally implemented as a singleton. The application object is a singleton and it maintains but one delegate object so you've only got one instances of the Core Data stack and since the application object is universally accessible, you can always get to the app delegate as well.

However, even that works only for simple apps with one persistent store with all the context using that one store. In more complex apps you may have multiple stores or context so a singleton quickly becomes too bloated.

A singleton usually won't buy you much complexity hiding or save duplicate coding because most of the coding you have to do with Core Data is in the controller layer where you link up the model to the view/interface. Since that logic is usually custom to each view, you can't actually park it in the singleton.

I've used singletons in the past but in the end they usually prove more hassle than they are worth.

like image 95
TechZen Avatar answered Sep 22 '22 14:09

TechZen


There are two important considerations (note these are not the only two) when deciding if a singleton is right for you:

  1. Threading
  2. Memory Usage

Threading

Singletons are convenient, but if your application uses multiple threads you might be tempted to write something like this:

[[CDSingleton managedObjectContext] executeFetchRequest:someFetch];
//later on a background thread you might write
NSManagedObject *object = [[CDSingleton managedObjectContext] objectWithID:objectID];

Shortly after that, your application will crash because you've accessed a managedObjectContext which was likely created on the main thread from some other thread.

Memory Usage

Singletons never go away, that's the point of a Singleton. Thus, they also never willingly free their consumed resources. In the case of CoreData that means the managed object context will continue to hold managed objects in memory until you call -reset or -save:.

That could be bad if your app uses a lot of data.

like image 25
ImHuntingWabbits Avatar answered Sep 26 '22 14:09

ImHuntingWabbits