JordiVilaplana
JordiVilaplana

Reputation: 485

Core data relationship lost after editing nested object

I have an entity named Geometry which is related to a Plot entity. In our piece of code, given the Plot and some downloaded data stored in a NSDictionary, we must get the Geometry and set some NSString properties but, after doing that, I find that the relationship between entities is lost.

NSError * saveError = nil;

NSFetchRequest * request = [[NSFetchRequest alloc] initWithEntityName:[Geometry entityName]];
request.predicate = [NSPredicate predicateWithFormat:@"plot == %@", plot];
NSError * error = nil;
NSArray * results = [context executeFetchRequest:request error:&error];

Geometry * __block geometry = nil;

if ([results count] > 0) {
    [results enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL * stop) {
        Geometry * geometryObject = obj;
        if ([geometryObject.gid isEqualToString:[NSString stringWithFormat:@"%@", [data valueForKey:@"gid"]]]) {
            geometry = geometryObject;
            stop = YES;
        }
    }];
}

if (geometry != nil) {
    [geometry setPolygon:[NSString stringWithFormat:@"%@", [data valueForKey:@"polygon"]]];
}

if (![context save:&saveError]) {
    NSLog(@"%@", saveError);
}

The first time I run this code results have one object, but the next time I run this there is no results.

Assume everything outside the scope of this piece of code is working right. Any hint or clue about why this happen? How can I solve this?

EDIT: The problem has been solved outside the scope of the code posted and outside the scope of this question. I should have properly reviewed the code further.

Upvotes: 0

Views: 67

Answers (1)

Mundi
Mundi

Reputation: 80265

There is nothing in your code that breaks the relationship. The error must be elsewhere.

You have a Plot object, so you can get the geometries with plot.geometries without a fetch request, and filter them without a loop:

Geometry *geometry = [plot.geometries
   filteredArrayUsingPredicate: [NSPredicate predicateWithFormat:@"gid = %@", gidString]]
   .firstObject

where geometries is the name of the inverse relationship for plot.

You can now set the polygon property and save. Check your setPolygon method if you are not removing the relationship.

Upvotes: 1

Related Questions