简体   繁体   English

iPhone CoreData:我应该如何将许多子实体与其父母联系起来

[英]IPhone CoreData: How should I relate many child entities to their parents

I am trying to import data from a database that uses primary key / foreign key relations to a core data database in Xcode. 我正在尝试从使用主键/外键关系的数据库中的数据导入Xcode中的核心数据数据库。

I have code that creates hundreds of child entities in a managed object context: 我有在托管对象上下文中创建数百个子实体的代码:

Each child has an ID that corresponds to a parent. 每个孩子都有一个对应于父母的ID。

child1    parentID = 3
child2    parentID = 17
child3    parentID = 17
...
childn    parentID = 5

I now need to relate each child to its parent. 我现在需要将每个孩子与其父母联系起来。 The parents are all stored in persistent memory. 父母都存储在持久性存储器中。

My first thought was to preform a fetch for each child to get its parent. 我的第一个想法是为每个孩子准备一个获取父母的东西。 However, I think this would be slow. 但是,我认为这会很慢。

Am I correct? 我对么? How should I do this instead? 我应该怎么做呢?

Why are you modeling this parent-child relationship using an attribute in the child entity? 为什么要使用子实体中的属性对此父子关系建模? You should model this using a to-many relationship from the parent entity to the child entity, and a to-one inverse relationship from the child to the parent entity. 您应该使用从父实体到子实体的一对多关系,以及从子实体到父实体的一对一逆关系来对此建模。 Set on delete cascade on the to-many relationship and nullify on the to-one relationship. 在一对多关系上设置删除级联,并在一对一关系上设置为无效。

Then, once you have a child object you simply use the to-one relationship to the parent entity to access the child's parent. 然后,一旦有了子对象,就可以简单地使用与父实体的一对一关系来访问子对象的父对象。

I have been looking at a few examples and have decided that the best approach would be the following 我一直在看几个例子,并决定最好的方法是

1) Fetch all the parents 1)获取所有父母

2) Transfer them into a dictionary with their parentID as the key 2)将其转移到以其parentID为键的字典中

Then for each child, look up its parent in the dictionary, then relate them together. 然后,对于每个孩子,在字典中查找其父母,然后将它们联系在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM