Refresh ManagedObjectContext Link

in my iOS application, I have basic data, and I noticed that sometime in a specific view, when I extract information from the main data, it is not always updated, I explain well:

if I update some value in the master data, and then I enter a specific view to view this information, this information is not updated, now I show how I access my database:

.h

@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext; 

.m

 @synthesize managedObjectContext; - (NSArray *)sortInformation{ if (managedObjectContext == nil) { managedObjectContext = [(AppDelegate *) [[UIApplication sharedApplication] delegate] managedObjectContext]; } NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; .... 

and then I display my information in a table, everything works fine, there is only this problem, SOME TIMES it seems that the update I made in another view is not read in that view, but if I close the application and I close it from the background, and then re-open everything that works well ... so I correctly saved the update in the main data, so I think the problem is in this view, maybe I have an old link to the update version and not, maybe the problem is as follows:

 if (managedObjectContext == nil) { managedObjectContext = [(AppDelegate *) [[UIApplication sharedApplication] delegate] managedObjectContext]; } 

which are only updated if the managedObjectContext variable is zero, only if the view is freed ... therefore never, because it is one of my root view controllers in the UITabbarController, so my question is how can I access the main data always have an update version?

+4
source share
2 answers

there is no need to update the context, just call the save method on managedObjectContext, for example [managedObjectContext save]; or if you use more than one managed entity context, you must merge the changes made by the context

+1
source

In the implementation of the database class, you can do this

 -(id) initWithContext: (NSManagedObjectContext *)managedObjContext { self = [super init]; [self setManagedObjectContext:managedObjContext]; return self; } 

managedObjContext is passed and set

There should be something like this in your delegate deletion when calling the database class

 database = [[Database alloc] initWithContext:self.managedObjectContext]; 

Then you can access a database like this

 - (NSArray *)sortInformation { NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; NSMutableArray *mutableFetchResults = [[[managedObjectContext_ executeFetchRequest:request error:&error] mutableCopy] autorelease]; [request release]; return mutableFetchResults; } 
0
source

All Articles