objective c - Import AppDelegate into models? -
i'm trying unify of functions of specific class within model file. instance, have function fetchcontactwithname:(nsstring *)name in model 'contact.h/contact.m', viewcontroller subsequently call.
in case, bad idea import appdelegate.h file model file need access managedobjectcontext?
#import "appdelegate.h" @implementation contact ... + (contact *) fetchcontactwithname:(nsstring *) name { appdelegate *delegate = (appdelegate*)[[uiapplication sharedapplication] delegate]; nsfetchrequest *fetchrequest = [[nsfetchrequest alloc] init]; nsentitydescription *entity = [nsentitydescription entityforname:@"contact" inmanagedobjectcontext:delegate.managedobjectcontext]; [fetchrequest setentity:entity]; nspredicate *predicate = [nspredicate predicatewithformat:@"name == %@", name]; [fetchrequest setpredicate:predicate]; nserror *error = nil; nsarray *fetchedobjects = [delegate.managedobjectcontext executefetchrequest:fetchrequest error:&error]; contact *fetchedcontact; for(contact *contact in fetchedobjects) { fetchedcontact = contact; } if(fetchedcontact != nil) { return fetchedcontact; } else { return nil; } } @end
in opinion it's bad idea directly ask different class managed object context. because
- you can't reuse classes in different projects (think os x app)
- you can't fetch contacts in different context (think background import)
- you can't use unit tests if method asks other class
you should tell method in context should fetch.
instead of + (contact *) fetchcontactwithname:(nsstring *) name
method signature should this:
+ (contact *)fetchcontactwithname:(nsstring *)name inmanagedobjectcontext:(nsmanagedobjectcontext *)context
each viewcontroller should have reference nsmanagedobjectcontext used in app delegate. can pass reference of context each viewcontroller in application:didfinishlaunchingwithoptions:
, , each time push or present new viewcontroller pass context instance it.
this might lot of work now, day benefit "tell, don't ask" approach.
Comments
Post a Comment