Setting up a parent-child relationship in Core Data

纵饮孤独 提交于 2019-11-27 13:49:31

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.

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