tungsten tungsten - 11 months ago 22
Objective-C Question

appDelegate managedObjectContext spread across codebase

When using core data. I find myself writing the code

AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [delegate managedObjectContext];

// Code here

[context save:nil];

everywhere in the codebase. Is this normal or is this an antipattern? I usually only use one context.


If you are using Core Data on several places in the app, you could use a Singleton class which handles the basic Core Data logic and holds the persistentStoreCoordinator, managedObjectModel and of course the wanted managedObjectContext.

@interface DataManager : NSObject

+ (DataManager *)sharedManager;

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (void)saveContext;


Then you can use the context anywhere like this

#import "DataManager.h"


NSManagedObjectContext *managedObjectContext = [[DataManager sharedManager] managedObjectContext];

// Do some Core Data action

I wouldn't recommend to add a property on AppDelegate since the AppDelegate is there for handling Application events, not storing data. It's just cleaner. By the way.. I always try to follow the "Single Responsibility Principle" (https://en.wikipedia.org/wiki/Single_responsibility_principle)