views:

45

answers:

2

I am trying to import data from a database that uses primary key / foreign key relations to a core data database in 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.

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?

+3  A: 

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.

unforgiven
Yes this is how it is modelled. Unfortunately I am getting the data from a external database, that uses the primary key/forign key design. I need to bridge the relationship once, then I can forget the parentID.
Robert
A: 

I have been looking at a few examples and have decided that the best approach would be the following

1) Fetch all the parents

2) Transfer them into a dictionary with their parentID as the key

Then for each child, look up its parent in the dictionary, then relate them together.

Robert