R – Most recent search results join in Core Data

core-dataiphone

This is a follow up question to a previous post on saving recent searches with Core Data.

To group search results, I have an Entry entity and History entity. Entry.history is a relationship to History. History.entries is a to-many relationship to Entry (the inverse of Entry.history). History has a date attribute createdAt. I am trying to figure out how to get all Entry entities that belong to the most recent History entity in a NSFetchedResultsController.

I can get the most recent History entity like so

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"History" inManagedObjectContext:context];
    [request setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [request setSortDescriptors:sortDescriptors];
    [request setFetchLimit:1];
    NSArray *results = [context executeFetchRequest:request error:&error];
    History *history = (History *)[results objectAtIndex:0];

And then the Entry entities in the NSFetchedResultsController like so

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"history == %@", history];
    request = [[NSFetchRequest alloc] init];
    entity = [NSEntityDescription entityForName:@"Entry" inManagedObjectContext:context];
    [request setEntity:entity];
    [request setPredicate:predicate];
    fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:nil cacheName:@"Root"];

But I want to do this in a single request. Please note I only care about the fetchedResultsController storing Entry results.

Best Solution

You should be able to have a sort descriptor that follows relationships:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entry" 
                                          inManagedObjectContext:context];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] 
                                    initWithKey:@"history.createdAt"
                                      ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&sortDescriptor
                                                      count:1];
[request setEntity:entity];
[request setSortDescriptors:sortDescriptors];
[request setFetchLimit:1];
fetchedResultsController = [[NSFetchedResultsController alloc]
                            initWithFetchRequest:request
                            managedObjectContext:context 
                              sectionNameKeyPath:nil 
                                       cacheName:@"Root"];
Related Question