Setting up a parent-child relationship in Core Data

时光总嘲笑我的痴心妄想 提交于 2019-11-26 16:29:46

问题


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?


回答1:


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

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.



来源:https://stackoverflow.com/questions/15232092/setting-up-a-parent-child-relationship-in-core-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!