Reputation: 1910
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?
Upvotes: 0
Views: 300
Reputation: 539745
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.)
Upvotes: 1
Reputation: 21
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.
Upvotes: 0
Reputation: 446
you can use NSDictionary or NSMutableDictionary that holds your objects in n<->n relation.
Upvotes: 0