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?
Sections are not really meant to be shown if there are no rows in them. That is the way the
UITableViewis designed. If you really wanted to force it you would need to add logic to your datasource call of-numberOfRowsForSection:to make it appear that there is always one row and then you could play with the-heightForRowAtIndexPath:to try and hide the row.Having said that, it is a terrible idea. Let the sections hide themselves like they were designed to.