Revisiting the Core Data Singleton

Whilst I’m sure the idea of a Singleton for application wide variables is going to be good one, I must say that I’ve revisited this idea over the last couple of days, especially with the help of an article Core Data: Passing around a NSManagedObjectContext on the iPhone which helps to set the perspective (as it should be) to the idea of reusing interface elements (i.e. Views).  It seems reasonable that views will be reused when creating an iPad version of the app, but because the navigation on the iPad encourages a flatter user experience, views will appear in different places.

As a result, I’ve re-engineered my app to remove the Singleton for the time being, and have gone with the conventional wisdom of creating the [cci]NSManagedObjectContext[/cci] in the [cci]AppDelegate[/cci], then passing a pointer to it into the relevant views.  Table Views for example receive a pointer, and then pass pointers to individual [cci]NSManagedObject[/cci]’s into detail views as appropriate (each [cci]NSManagedObject[/cci] contains a reference to the [cci]NSManagedObjectContext[/cci] to which it belongs, allowing the sub-view to perform any additional data manipulation).

The following code shows how this might work in practice:


[cc lang="objc" width="auto"]
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    GroupTableViewController *table = (GroupTableViewController *) navigationController.topViewController;
    table.managedObjectContext = self.managedObjectContext;

    [window addSubview:navigationController.view];
    [window makeKeyAndVisible];

    return YES;


[cc lang="objc" width="auto"]
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Get the group object from the fetched results controller (which is created from
    // the managedObjectContext passed to the GroupTableViewController)
    Group *group = [self.fetchedResultsController objectAtIndexPath:indexPath];
    DetailViewController *detailView = [[DetailViewController alloc] init];
    detailView.delegate = self; = group;

    [self presentModalViewController:detailView animated:YES];
    [detailView release];

2 thoughts on “Revisiting the Core Data Singleton

  1. Any idea how to get this workng with a tabbarcontroller in the mix? Happen to have an example code that is using storyboards that you could post?

    Any way, thanks for the info!

Leave a Reply

Your email address will not be published. Required fields are marked *