OdieO
OdieO

Reputation: 6994

Set Relationship of two newly created Core Data objects

A really simple question I can't find an answer for. I have my Core Data entities subclassed - Area and GPS and I'm setting them up with data from a JSON file. That seems fine. But how do I setup the relationship between the two newly created Entity objects?

    NSManagedObjectContext *context = [self managedObjectContext];
    Area *area = [NSEntityDescription
                                  insertNewObjectForEntityForName:@"Area"
                                  inManagedObjectContext:context];

    GPS *gps = [NSEntityDescription
                                 insertNewObjectForEntityForName:@"GPS"
                                 inManagedObjectContext:context];

    NSDictionary *attributes = [[area entity] attributesByName];

    for (NSString *attribute in attributes) {
        for (NSDictionary * tempDict in jsonDict) {  
            id value = [tempDict objectForKey:attribute];

            if ([value isEqual:[NSNull null]]) {
                continue;
            }

            if ([attribute isEqualToString:@"latitude"] || [attribute isEqualToString:@"longtitude"]) {
                [gps setValue:value forKey:attribute];
            }
            else {
                [area setValue:value forKey:attribute];
            }
        }

        [area setAreaGPS:gps]; // Set up the relationship
        }

The name of the relationship from Area to GPS is areaGPS

The error:

 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for to-many relationship: property = "areaGPS"; desired type = NSSet; given type = GPS; value = <GPS: 0x369540>

I've seen this syntax of [area setAreaGPS:gps]; on a couple examples but apparently I'm not understanding how to use it correctly.

Upvotes: 1

Views: 1897

Answers (1)

Scott Berrevoets
Scott Berrevoets

Reputation: 16946

You have set the relationship up as a to-many relationship. Depending on how you define your areas, this could or could not have been a good choice. If one area can have multiple GPS objects associated with it, then you're good. All you need to change then is your [area setAreaGPS:gps] to:

NSMutableSet *mutableGPS = [area.areaGPS mutableCopy];
[mutableGPS addObject:gps];
[area setAreaGPS:mutableGPS];

If you only ever want one GPS object associated with an Area object, you'll have to change the relationship to not be a to-many relationship, but a to-one relationship. You don't need to change any code in that case (except for regenerating your NSManagedObject subclasses).

Upvotes: 3

Related Questions