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
?
Soleil,
This is quite simple. First of of all, your model should look like the following (for the sake of simplicity I skipped attributes).
In this case a Tree
can have zero or more Fruit
s (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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With