views:

360

answers:

1

I am working with a NSFetchedResultsController whose fetchRequest has a predicate. However, it seems that the query doesn't give me consistent groupings each time I execute it.

I've set the 'sectionNameKeyPath' for the NSFetchedResultsController and I get a different number of sections returned based on whether I have been working with the root object immediately prior to running the fetch. Sometimes I get 3 sections and other times, it returns 1 section, the expected result.

How I am creating the FetchRequestController:

// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

// Configure the request's entity and its predicate.     
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Employee"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];

// The predicate to find all employees associated with a Group
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.groups IN %@",
          [division groups]];

[fetchRequest setPredicate:predicate];

// Sort based on create date and time
NSSortDescriptor *createDateSortDcptor = [[NSSortDescriptor alloc] initWithKey:@"createDateTime" ascending:YES];

NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:createDateSortDcptor, nil];

[fetchRequest setSortDescriptors:sortDescriptors];

// should be grouped by the 'Group' employee belongs to.
NSFetchedResultsController *controller = 
  [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
      managedObjectContext:context 
      sectionNameKeyPath:@"groups" 
      cacheName:@"Root"];

My object model is the same that was outlined in this other question:

http://stackoverflow.com/questions/1580236/how-to-setup-a-predicate-for-this-query Is there a way to make sure I am getting consistent grouping each time?

A: 

It turns out that it's simple as doing:

NSFetchedResultsController *controller = 
  [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
      managedObjectContext:context 
      sectionNameKeyPath:@"groups.name" 
      cacheName:@"Root"];

I didn't realize I could append 2nd level property names within the 'sectionNameKeyPath'

Alexi Groove