ios - appDelegate managedObjectContext spread across codebase -
when using core data. find myself writing code
appdelegate *delegate = [[uiapplication sharedapplication] delegate]; nsmanagedobjectcontext *context = [delegate managedobjectcontext]; // code here [context save:nil];
everywhere in codebase. normal or antipattern? use 1 context.
if using core data on several places in app, use singleton class handles basic core data logic , holds persistentstorecoordinator
, managedobjectmodel
, of course wanted managedobjectcontext
.
@interface datamanager : nsobject @property (readonly, strong, nonatomic) nsmanagedobjectcontext *managedobjectcontext; @property (readonly, strong, nonatomic) nsmanagedobjectmodel *managedobjectmodel; @property (readonly, strong, nonatomic) nspersistentstorecoordinator *persistentstorecoordinator; + (datamanager *)sharedmanager; - (void)savecontext; @end
then can use context anywhere this
#import "datamanager.h" ... nsmanagedobjectcontext *managedobjectcontext = [[datamanager sharedmanager] managedobjectcontext]; // core data action
i wouldn't recommend add property on appdelegate since appdelegate there handling application events, not storing data. it's cleaner. way.. try follow "single responsibility principle" (https://en.wikipedia.org/wiki/single_responsibility_principle)
Comments
Post a Comment