kupilot
kupilot

Reputation: 504

Swift core data many-to-many relationship

Swift Core Data many-to-many relationship , how do you save the relationship.

lets suppose there is 2 entities Event and Member, an event can have many members associated with and a Member can have many events...

so

Event <<-->>Member

relationship

events - Event - members members - Member - events

how would you code saving this kind of relationship?

Upvotes: 0

Views: 1446

Answers (1)

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20379

You dont have to any code to establish the relationship between entities Event and Member buddy :)

You can open up core data model, select the Event entity, hold the control and drag the mouse over Members entity :) Relationship will be established immediately :)

Now select the relationship change it to many to many from both Event to Member(many-to-many-relationship) and Member to Event(inverse relationship) :)

Now name those relationships at both Event and Member entity appropriately :)

Like Many to Many relationship in event be named as involves_Members and same relationship in Member entity will be named as involvedin_Events :)

Now when you generate the model classes for both entities you will find

Events.h

has a property named involves_Members which will be of type NSSet

and similarly

`Members.h`

has a property named involvedin_Events which will be of type NSSet as well :)

Now assume if you want to add the member to Events all you have to do would be

create a Member object as

    [context performBlock:^{

    Member *member = (Member *)[NSEntityDescription insertNewObjectForEntityForName:@"Member"  inManagedObjectContext:context];
    [member setValue:@"yourValue" forKey:@"yourkey"];
    //after populating it with appropriate value set the relationship with event :)
    //get the event to which you want to set the relationship with member using NSFetchRequest :)

    //assuming you have event object with you 
    NSMutableSet *involvedMembers = [event mutableSetValueForKey:@"involves_Members"];
    [involvedMembers addObject:member];

    [event setValue:involvedMembers forKey:@"involves_Members"];

    //thats it you are done now 
    //save the context now :)
    NSError *error;  
    [context save:&error];
}];

And when you want to access all the members involved in and event all you have to do is to get the event object using NSFecthRequest :) and once you have the event object you can access all its members by using,

NSArray *membersArray = [event.involves_Members allObjects];

OR

NSArray *membersArray = [event valueForKey:@"involves_Members"];

That's it :) Same thing is applicable for members enity as well :)

TIP

You dont want the delete operation to mess with your core data :) So select both the relationships involves_Members and involvedin_Events and set the delete rule to Nullify

Hope I made my point clear :) Happy coding buddy :)

Upvotes: 3

Related Questions