Core Data 1-to-many relationship: List all related objects as section header in UITableView

Posted by Snej on Stack Overflow See other posts from Stack Overflow or by Snej
Published on 2010-02-25T19:58:23Z Indexed on 2010/04/28 3:53 UTC
Read the original article Hit count: 398

Hi: I struggle with Core Data on the iPhone about the following: I have a 1-to-many relationship in Core Data. Assume the entities are called recipe and category. A category can have many recipes. I accomplished to get all recipes listed in a UITableView with section headers named after the category. What i want to achieve is to list all categories as section header, even those which have no recipe:

category1   <--- this one should be displayed too
category2
     recipe_x
     recipe_y
category3
     recipe_z

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

 NSEntityDescription *entity = [NSEntityDescription entityForName:@"Recipe" inManagedObjectContext:managedObjectContext];
 [fetchRequest setEntity:entity];
 [fetchRequest setFetchBatchSize:10];

 NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"category.categoryName" ascending:YES];
 NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"recipeName" ascending:YES];
 NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1,sortDescriptor2, nil];

 [fetchRequest setSortDescriptors:sortDescriptors];
 NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"category.categoryName" cacheName:@"Recipes"];

What is the most elegant way to achieve this with core data?

© Stack Overflow or respective owner

Related posts about iphone

Related posts about core-data