ios - Detect change in NSManagedObjectContext in app delegate from different class? -
i have nsmanagedobjectcontext in app delegate , data loaded , saved fine. call nsmanagedobjectcontext master view controller , load data there. have problem when new data saved nsmanagedobjectcontext don't know how detect change , reload table in master view controller. guessing use nsnotification possible use nsnotification in master view controller nsmanagedobjectcontext in app delegate?
i tried implement code context nsmanagedobjectcontext app delegate (this won't work obviously). suggestions on how detect change in data?
[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(handledidsavenotification:) name:nsmanagedobjectcontextdidsavenotification object:context]; if (![context save:&error]) { nslog(@"there change"); }
firstly, view controller should using managed object context created app delegate (for main thread). if app delegate doing significant data loading should create managed object context purpose , on background thread.
if can, view controller should use nsfetchedresultscontroller source data managed object context. provides easy mechanism getting data required displayed , (if make view controller frc delegate) monitor changes managed object context , tell when table view needs reloaded.
if can't use nsfetchedresultscontroller, notification method should work fine. code show above add self (which i'm assuming view controller) observer. should when view loaded , handledidsavenotification: called when need reload table view. remember remove observer when view unloaded , when view controller deallocated.
from comment, say:
i use nsfetchedresultscontroller , data loaded array populates table
don't that... use nsfetchedresultscontroller data, don't copy array - destroys of benefit of nsfetchedresultscontroller. instead:
make delegate of
nsfetchedresultscontroller, incontrollerdidchangecontent:need[self.tableview reloaddata];.in table view delegate method
tableview:cellforrowatindexpath:, usensfetchedresultscontrollerobject data displayed on cell usingobjectatindexpath:.
please read ray wenderlich nsfetchedresultscontroller guide here.
Comments
Post a Comment