Most recent search results are merged into Core Data
This is the next question to the previous post, saving recent searches using master data.
To group the search results, I have an Entry object and a History element. Entry.history is a relation to History. History.entries is a to-many relationship to Entry (inverse to Entry.history). History has a date attribute createdAt. I'm trying to figure out how to get all the Entities belonging to the most recent History object in the NSFetchedResultsController.
I can get the most recent history object like this:
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 Entry objects in NSFetchedResultsController for example
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 it in one request. Note that I don't care that fetchedResultsController stores the results of the input.
a source to share
You must have a sort descriptor that follows the relationship:
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"];
a source to share