Question

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?

Was it helpful?

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.)

OTHER TIPS

you can use NSDictionary or NSMutableDictionary that holds your objects in n<->n relation.

The Core Data Programming Guide on Apple's developer site is very thorough. There is a section in the middle of the page at the link below that covers how to create a many-to-many relationship.

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/Articles/cdRelationships.html#//apple_ref/doc/uid/TP40001857-SW10

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top