0

Let's say that my Core Data model contains the following entity, Family:

enter image description here

I'd like to use NSFetchedResultsController to display the contents of the Family in a UITableViewController in the following format where parents are "sections" with children listed under a "parent":

enter image description here

In my view controller file, I have the following:

- (void)setFRC
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:[Family entityName]];

    NSSortDescriptor *sort1 = [[NSSortDescriptor alloc] initWithKey:@"Child" ascending:YES];
    NSSortDescriptor *sort2 = [[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES];

    NSArray *sorters = [NSArray arrayWithObjects:sort1, sort2, nil];

    [request setSortDescriptors:sorters];

    self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:[MYCoreDataManager managedObjectContext] sectionNameKeyPath:@"Child" cacheName:nil];
}

When using the code above, however, I'm getting the following table instead:

enter image description here

Can somebody tell me how to get the "children" grouped underneath the proper "parent"? I realize that the data model could be separated such that there are separate entities for child and parent; however, I'm working with legacy code and don't have the luxury of modifying the data model for the time being.

Vee
  • 1,821
  • 3
  • 36
  • 60
  • I think you have to use predicate for getting the child of same parent with your sorting array key. with that you can get filtered array like children of Alam or children of Cain. – Jitendra Modi Feb 01 '17 at 06:27
  • Did you try `sectionNameKeyPath:@"ParentName"`? – norders Feb 01 '17 at 07:47
  • @JeckyModi - can you explain with an example? Not sure what you mean by that. – Vee Feb 01 '17 at 15:34
  • @norders - using ParentName results in the same prob where the parents are grouped together followed by all the children. – Vee Feb 01 '17 at 15:34

1 Answers1

0

I think you need to use predicates:

  1. Get all Parents

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Child == %@", @NO];

  2. Loop through the parents and get all their Children

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Child == %@ AND Parent == %@", @YES, parent.Name];

This solution results in an array construct. Not sure, this answer is helping you, since you're looking for a NSFetchedResultsController.

Marco
  • 1,276
  • 1
  • 10
  • 19
  • Thanks, Marco. Yes, you're right about getting the parents and then building the array construct for children for each parent. But, I'm looking for a solution that uses NSFetchedResultsController. – Vee Feb 01 '17 at 15:27