Search code examples
iphoneobjective-cxcodecore-dataentity-relationship

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?


Solution

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