Borut Tomazin
Borut Tomazin

Reputation: 8138

How to create proper iOS CoreData database model?

I have been learning CoreData to use it in my application and have some problems generating sql model.

I would like to have two entities (at least). One is Items, other is History. Logic: every history entity should have none or many Items. Items shouldn't duplicate each other - uniques.

How can I model this in Xcode? Do I need a linking entity like "History2Items"?

I have been struggling this for a while but I can figure it out the proper solution.

Any help?

UPDATE:

I have made this model:

CoreData model

For fetching data I used relationship for prefetching:

[request setRelationshipKeyPathsForPrefetching:[NSArray arrayWithObject:@"item"]];

And that's how I get Items for each History:

History *history = [self.historyArray objectAtIndex:indexPath.row];
NSMutableArray *items = [NSMutableArray arrayWithArray:[history.item allObjects]];

Just looped over items array to get each Item.

It's that easy. Thanks to @Ashley Mills.

Upvotes: 2

Views: 542

Answers (1)

Ashley Mills
Ashley Mills

Reputation: 53082

Create Item and History entities and connect them as follows:

enter image description here

If an Item can belong to more than one History, change the relationship from one-to-many to a many-to-many.

You only need a linking entity if you intend on ordering the items for a history by an index, as each item could have a different index for a given history. If you're ordering items by date for example, no linking entity would be required.

Upvotes: 2

Related Questions