Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up a parent-child relationship in Core Data

I'm trying to set up a relationship in Core Data. I have a list of Trees, and each Tree will have a list of Fruits. So I have a Tree entity and a Fruit entity.

In code, I will want to list the Trees, in a table view for example. When you click on a Tree, it should then display a list of fruits that growing on that Tree.

How do I set up this relationship? Do I need to give the Fruit an attribute called tree? And how do I set the relationship in code, for example when I create a Fruit how do I associate it with a given Tree?

like image 904
soleil Avatar asked Mar 05 '13 19:03

soleil


1 Answers

Soleil,

This is quite simple. First of of all, your model should look like the following (for the sake of simplicity I skipped attributes).

enter image description here

In this case a Tree can have zero or more Fruits (see fruits relationship). On the contrary, a Fruit has a tree relationship (an inverse relationship).

In particular, the fruits relationship should look like the following

enter image description here

Here, you can see that a to-many relationship has been set. The Delete rule means that if you remove a tree, also its fruits will be deleted.

The tree relationship is like the following

enter image description here

This is a one-to-one relationship since a fruit can exist only if attached to a tree. Optional flag is not set. So, when you create a fruit you also need to specify its parent (a tree in this case). Nullify rule means that when you delete a fruit, Core Data will not delete the tree associated with that fruit. It will delete only the fruit you specified.

When you create a Fruit entity you should follow a similar path

NSManagedObject *specificFruit = [NSEntityDescription insertNewObjectForEntityForName:@"Fruit" inManagedObjectContext:context];
[specificFruit setValue:parentTree forKey:@"tree"];

or if you have create NSManagedObject subclasses:

Fruit *specificFruit = [NSEntityDescription insertNewObjectForEntityForName:@"Fruit" inManagedObjectContext:context];
specificFruit.tree = parentTree;

Hope that helps.

P.S. Check the code since I've written without Xcode support.

like image 120
Lorenzo B Avatar answered Sep 28 '22 16:09

Lorenzo B