I am new to iPhone development trying to figure out how to setup a one to many relationship Core Data. I have two Entities setup One Leagues which has a one to many relationship to an entity Teams. So lot’s of teams in a league. Think all the teams that play baseball and are in the MLB.
I am pre-filling the data when the user first enter’s their username and password, so I have the leagues populate first, which I have no problem with. Then when I begin adding the teams I do a search looking for league. Code is below.
- (NSMutableSet *)checkItem:(int *)identifier inTable:(NSString *)table inContext:(NSString *)context {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:table inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:context,identifier];
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray *items = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];
if ([items count] >= 1) {
return [items objectAtIndex:0];
} else {
return nil;
}
}
By calling this and then set up the team entry and save (‘league’ is my relationship):
NSMutableSet *leagueObjectSet = [self checkItem:lid inTable:@"Leagues" inContext:@"id=%i"];
NSManagedObject *teamObject = [NSEntityDescription insertNewObjectForEntityForName:@"Teams" inManagedObjectContext:managedObjectContext];
[teamObject setValue:[NSNumber numberWithInt:tid] forKey:@"id"];
[teamObject setValue:[dict valueForKey:@"name"] forKey:@"teamName"];
[teamObject setValue:leagueObjectSet forKey:@"league"];
[self saveAction];
When I run this I get this error message in the console.
“the entity Teams is not key value coding-compliant for the key “league”.”
Am I doing this right? With everything I have read it seems like I am. I come from a MySQL background so be gentle!
From your description, I believe that you have a wrong setup for your one to many relationship. Assuming you have two entities named League and Team, and that you have correctly setup the relationship, when you want to relate a team to a league, your league object must not be a
NSMutableSetas shown in your code snippet: it must be aNSManagedObjecttoo. A League object, being on the to many side of the relationship will have a property named teams or similar which will be aNSMutableSet. A Team object, on the one side of the relationship will have instead a property named league or similar which is a League object.Then, to setup the relationship you can do as you did using key value coding, but for performance reasons it is best to do
This is much faster and suggested by Apple.