Search code examples
ioscore-dataentity-relationship

How to create a Core Data relationship with two existing objects


I've created a many-to-many relationship between two entities: event<<-->>team. Selecting an event brings you to a detail page where you can change settings/associate teams that will partake in the event. The team page presents the user with a list of teams (created earlier in the process) that can be selected (with a checkmark) to associate to the event. The event MOC is passed to the team view which has its own MOC for team. When you select the team(s) that will participate in the event, I'm having trouble creating the relationship to the event. In the save method:

-(void)add 
{
for (int i = 0; i < dataArray.count; ++i) 
{
    NSDictionary *item = [dataArray objectAtIndex:i];

    NSString *name = [item valueForKey:@"teamName"];
    BOOL isChecked = [[item valueForKey:@"teamChecked"] boolValue];

    if (isChecked != 0)
    {

        NSManagedObjectContext *context = [event managedObjectContext];
        Team *team = [NSEntityDescription insertNewObjectForEntityForName:@"Team" inManagedObjectContext:context];

       [event addTeamsObject:team];

        team.teamName = name;

        NSError *error = nil;
        if (![context save:&error]) 
        {

            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }

    }

} 

[self dismissModalViewControllerAnimated:YES];
}

The problem with the code is that the insertNewObjectForEntity takes the team that is selected and creates a new duplicate team that is associated to the event. How can I just associate the selected team(s) to the event? Any help is greatly appreciated!


Solution

  • Ok, this should not be necessary if your many-to-many has each relationship correctly modelled as having the "back relationship" set to the other one in the .xcdatamodel (or .xcdatamodeld) file. However, you can just try, after this:

       [event addTeamsObject:team];
    

    add this

       [team addEventsObject:event];
    

    Essentially forcing the back relationship yourself.

    However from your code it could also be that there is already a team by a particular teamName that you want to associate said event with. In that event, you have to not insert a new team object - just fetch the existing team object and set the relationship methods instead.