Search code examples
ioscore-dataiphonecoredatarecipes

How to handle a one-to-many relationship in CORE DATA


I have a problem in core data where I am using both one-to-one and one-to-many relationships.

1. Lets consider a parent entity P1 and child entities C1,C2,C3.

2. C3 has 3 more child entities C31,C32,C33.

3. If I update or delete or change in C32 table, I will get full JSON from the server for the parent P1.

Is there any way to changes all child tables of a particular parent table? Basically, if any update or delete or change is done in child tables, I will get a new parent table with all child tables details from server.

Is there any way to handle this in core data?


Solution

  • More than handling relationship in Core Data, you question is about how keeping in sync a remote database exposed through a JSON-based API and your local Core Data mirror.

    The naive way, in the scenario you depicted, is:

    1. you get a full JSON from the server;

    2. with this, identify your parent entity (based e.g. on its ID);

    3. delete the parent entity from your local database; if you set up your model properly, all children will w also be deleted;

    4. create the entity anew with all of its children.

    The other possible approach, is you get the full JSON, then compare each child in the JSON with each child in Core Data and delete those not present in the JSON.

    Finally, you could take into consideration RestKIT, which is a framework which will do all of this work for you -- there is some learning curve to go, but it will handle all details for you.