iOS Core Data - Deletes not reflected until App Restart
I am successfully adding and updating records in my core data on a second thread without issue.
However, deletes don't seem to take effect until I stop and restart the App. So the delete is obviously working to a extent. I read the data before loading the tableview and don't do anything different for when there has been a deletion.
The code I'm using is
....fetch records....
BOOL deleteGem = FALSE;
if ([[attributeDict objectForKey:@"headline"] hasPrefix:@"VOID"])
deleteGem = TRUE;
if ([mutableFetchResults c开发者_开发问答ount] == 0) {
// not there so create a new one
if (!deleteGem) {
// so create a new one unless it needs deleting
gem = (Gem *)[NSEntityDescription insertNewObjectForEntityForName:@"Gem" inManagedObjectContext:managedObjectContext];
[gem setID:[attributeDict objectForKey:@"ID"]];
}
} else {
// already exists so either get it and then update or delete it
gem = [mutableFetchResults objectAtIndex:0];
if (deleteGem) {
// delete it if required
[managedObjectContext deleteObject:gem];
gemDeletes ++;
}
}
.....
Later on I have a method to save any updates including:
NSError *error;
if (![self.managedObjectContext save:&error]) {
....
Any ideas warmly welcomed...
Edit - with full answer based on @TechZen's answer..
Register for notifications of updates on the 2nd thread in viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleSaveNotification:) name:NSManagedObjectContextDidSaveNotification object:nil];
Unregister for notifications in viewDidUnload
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSManagedObjectContextDidSaveNotification object:nil];
Handle the update in the main thread (a new method in the view controller)
-(void)handleSaveNotification:(NSNotification *)aNotification {
[managedObjectContext mergeChangesFromContextDidSaveNotification:aNotification];
}
You have to merge the background context with the foreground context if you want the changes made in the background context to show up in the foreground context.
精彩评论