问题描述
我想在Core Data中建立关系。我有一个树列表,每个树将有一个水果列表。所以我有一个树
实体和水果
实体。
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的属性吗?如何在代码中设置关系,例如当我创建一个水果
如何将它与给定的树
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).
在这种情况下,树
可以有零个或多个水果
(参见 fruits
关系)。相反, Fruit
具有树
关系(反向关系)。
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.
树
这是一个一对一的关系,因为水果只有连接到一棵树才能存在。未设置可选标志。所以,当你创建一个水果,你还需要指定其父(在这种情况下一棵树)。 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.
当您创建一个
水果
实体时,您应该遵循类似的路径
When you create a
Fruit
entity you should follow a similar path
NSManagedObject *specificFruit = [NSEntityDescription insertNewObjectForEntityForName:@"Fruit" inManagedObjectContext:context];
[specificFruit setValue:parentTree forKey:@"tree"];
或者如果您有create
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中设置父子关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!