5

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?

Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
soleil
  • 12,133
  • 33
  • 112
  • 183

1 Answers1

17

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.

Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
  • shouldn't tree be the one have the to-many relationship and not fruit? the other way around right? – lakshmen Mar 05 '13 at 21:08
  • @lakesh Maybe I didn't explain it well but as I wrote, a `Tree` can have zero or more fruits. A `Fruit` is associated with one tree. Does it work for you? – Lorenzo B Mar 05 '13 at 21:12
  • Great answer, thanks. I have done much of that but you filled in some details that will help a lot. – soleil Mar 05 '13 at 21:36