开发者

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

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];
 NSSortDescript开发者_StackOverflowor *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 UITableView is 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.


You can't do that cleanly with the sectionNameKeyPath code. I would modify the fetch request query the categories, and tell it to include sub entitites:

[fetchRequest setIncludesSubentities:YES];

This way it will be efficient in the query, and not faulting everywhere. From there fleshing out your delegate should be pretty simple.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜