Michael
Michael

Reputation: 1238

Core Data - please help me to build right data model

There is a model of flash card for learning terms and definition. I've created entity Card with the following attributes:

packTitle def level term

Cards in a set with definite theme have the same packTitle, for example animals. To populate all available packTitles I get an array

NSArray *arrayOfTitles = [[[fetchedResultsController fetchedObjects]
                                           valueForKey:@"packTitle"]
                                       valueForKeyPath:@"@distinctUnionOfObjects.self"];

to get all cards with definite packTitle

- (NSArray *) cardsForPackTitle:(NSString * )selectedPackTitle {

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Card" inManagedObjectContext:managedObjectContext];

    [fetchRequest setEntity:entity];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(packTitle like %@)", selectedPackTitle];

    [fetchRequest setPredicate:predicate];

    NSError *error;

    NSArray *fetchedCards =  [managedObjectContext executeFetchRequest:fetchRequest error:&error ];

    [fetchRequest release];

     return fetchedCards;  

}

All above works, but when I need to delete cards with definite packTitle, it seems that code become to long for the simple task.

The question: should I built the data model in may case some other way? I'm new to Core Data, sorry if the question is stupid.

Upvotes: 0

Views: 78

Answers (1)

Enchilada
Enchilada

Reputation: 3919

Yes, you should most probably do it differently. It doesn't make much sense to repeatedly store "animal" in various cards just to signify they're animal cards.

What you should (probably) do is create another entity called Pack. This entity should have the title attribute, and the cards one-to-many relationship. Then connect the cards relationship to your Card entity. (Remove the packTitle attribute from the Card entity.)

You should also read the Core Data Programming Guide to learn more about Core Data. It's a bit difficult to understand at first, but after a couple of reads and a little bit of practice it starts to make sense.

Upvotes: 1

Related Questions