Core Data - Breaking A Relationship
I have a Patient entity and a List entity. A Patient can belong to several different lists and a list can have several different patients.
Say I have a patient who belongs to 3 lists (A, B, C). 开发者_开发问答I want to remove the patient from lists A & B. I do not want to delete lists A & B themselves though obviously. How do I go about doing this?
While Tim's answer above is technically correct, it seems like quite a bit of code to me.
I would assume that to remove a patient from the list, you already know that list and have a reference to it at the time you want to remove the patient. Therefore, the code can be as simple as:
id myPatient = ...;
id myList = ...;
[[myPatient mutableSetValueForKey:@"lists"] removeObject:myList];
This is of course assuming that your relationships are bi-directional. If they are not then I strongly suggest you make them bi-directional.
Lastly, because this is a many to many relationship, you can execute the above code in either direction.
[[myList mutableSetValueForKey:@"patients"] removeObject:myPatient];
update
Then the code is even simplier:
[myPatient setLists:nil];
That will remove the patient from all lists.
So in order to model this relationship, you have a many-to-many relationship between Patient and List. Let's say that in Core Data, this is represented by a patients
relationship on List, with the inverse lists
relationship on Patient. Furthermore let's assume that List has some property name
with the name of the list, as an NSString.
In order to "break" the relationship (remove a Patient from some Lists), you'll have to have a reference to the Patient NSManagedObject that is to be removed, and the Lists you want to remove that Patient from. Then, all that remains to be done is get a mutable set of the patients for each list, and remove the desired patient:
// Assuming you have some PatientManagedObject *patient:
NSSet *patientLists = [patient lists]; // Set of ListManagedObjects
for(ListManagedObject list in patientLists) {
if([[list name] isEqualToString:@"A"] || [[list name] isEqualToString:@"B"]){
// Now you have to build the set of patients without this patient
NSMutableSet *listPatients = [list mutableSetValueForKey:@"patients"];
[listPatients removeObject:patient];
}
}
For more data, see the relevant Core Data documentation.
精彩评论