Question

I am having issues trying to get my CoreData to save, I have used CoreData before and don't normally run in to these issues. Can someone tell me what is wrong with the following code:

MapEntity *mapEntity = [_fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];

NSMutableSet *set = (NSMutableSet *)mapEntity.points;
[set removeObject:self.selectedPoint];

self.selectedPoint = nil;
[[Singleton sharedSingleton] saveContext];

To initialise my fetched results controlled I use the following:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"MapEntity" inManagedObjectContext:[[Singleton sharedSingleton] managedObjectContext]];

So the entity returned should definitely be in the singletons manabged object context. The code for saveContext is below:

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            NSLog(@"Unable to save context");
    }
    }
}

If I check the mapEntity.points after the removal of the object I can see the object has been removed. The object doesn't re-appear until I relaunch the app, so it must be a persistance issue. Can anyone figure out what's wrong with my code as I am completely baffled.

Was it helpful?

Solution

I have managed to fix the issue, seems it lied within the way I was deleting objects. Instead I am now using the set deletion functions created by CoreData, code below for anyone else with the same issues:

MapEntity *mapEntity = [_fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];

    NSSet *removeSet = [NSSet setWithObject:self.selectedPoint];
    [mapEntity removePoints:removeSet];

    self.selectedPoint = nil;
    [[Singleton sharedSingleton] saveContext];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top