Search code examples
iosobjective-ccocoa-touchcore-datamany-to-many

How do I set up a many-to-many relationship in iOS? (Core Data)


I'm relatively new to core data, and have used one-to-many relationships frequently. Yet I'm currently in a situation where having a many-to-many relationship makes sense. I have users and groups, users can have many groups and groups will have many users. Yet it occurred to me I have no clue how to set this up.

To add a user to a group I would normally do something like...

Group *group = [NSEntityDescription
                        insertNewObjectForEntityForName:@"Group"
                        inManagedObjectContext:_managedObjectContext];
group.user = myUser;

But now I have group.users (plural) and I can't figure out what I'm supposed to populate that with. Should it be an NSArray with my user objects? If so, does that mean every time I want to add a new user I first have to fetch all the current users, stick it in an array, update that array with the new user, then assign it group.users?

I can't imagine I'd have to do something that ridiculous; would someone give me a basic explanation as to how I build a many-to-many relationship?


Solution

  • The value of a to-many relationship is a NSSet, not an NSArray. But you can use the generated Core Data accessor methods to add an element to a to-many relationship. For example:

    User *user = ...;
    Group *group = ...;
    
    // Add user to group:
    [group addUsersObject:user];  // (1)
    // Or, alternatively, add group to user:
    [user addGroupsObject:group]; // (2)
    

    (You can do either (1) or (2). If the relationships are defined as inverse relationships of each other, one automatically implies the other.)