在 Core Data 中设置父子关系 [英] Setting up a parent-child relationship in Core Data
问题描述
我正在尝试在 Core Data 中建立关系.我有一个树列表,每棵树都有一个水果列表.所以我有一个 Tree
实体和一个 Fruit
实体.
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.
我如何建立这种关系?我需要给 Fruit
一个名为 tree 的属性吗?以及如何在代码中设置关系,例如,当我创建一个 Fruit
时,我如何将它与给定的 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).
在这种情况下,Tree
可以有零个或多个 Fruit
(参见 fruits
关系).相反,一个 Fruit
有一个 tree
关系(逆关系).
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).
特别是,fruits
关系应该如下所示
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.
tree
关系如下
这是一对一的关系,因为水果只有附着在树上才能存在.可选 标志未设置.所以,当你创建一个水果时,你还需要指定它的父级(在这种情况下是一棵树).Nullify 规则意味着当您删除一个水果时,Core Data 不会删除与该水果关联的树.它只会删除您指定的水果.
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.
当你创建一个 Fruit
实体时,你应该遵循类似的路径
When you create a Fruit
entity you should follow a similar path
NSManagedObject *specificFruit = [NSEntityDescription insertNewObjectForEntityForName:@"Fruit" inManagedObjectContext:context];
[specificFruit setValue:parentTree forKey:@"tree"];
或者如果您创建了 NSManagedObject
子类:
or if you have create NSManagedObject
subclasses:
Fruit *specificFruit = [NSEntityDescription insertNewObjectForEntityForName:@"Fruit" inManagedObjectContext:context];
specificFruit.tree = parentTree;
希望有所帮助.
附言检查代码,因为我是在没有 Xcode 支持的情况下编写的.
P.S. Check the code since I've written without Xcode support.
这篇关于在 Core Data 中设置父子关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!