views:

47

answers:

2

I have two entities: Department and DepartmentNews. Every Department has one or many DepartmentNews Objects. Inside DepartmentNews, there is an newsTitle attribute, and there is an releaseDate attribute.

I want to fetch all those Department objects and sort them by their associated DepartmentNews newsTitle with the latest releaseDate.

Is it possible to make a predicate for this? Probably with subqueries? How could something like this be done? I'm using the NSFetchedResultsController...

A: 

What do you think about just fetching the Departements and then use a key path for the sort descriptor. I try coding this up:

NSFetchRequest *allDepartements = [[NSFetchRequest alloc] init];
[allDepartements setEntity:[NSEntityDescription entityForName:@"departements"
inManagedObjectContext:moc]];
// now specify the sorting
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:@"departementNews.date"] ascending:YES];
[allDepartements setSortDescriptors:[NSArray arrayWithObject:sortDesc]];
[sortDesc release];
// performing the fetch without an NSFetchedResultsController
NSError *error = nil;
NSArray *result = [moc executeFetchRequest:allDepartements error:&error];
[allDepartements release];

What you get is an array of Departements sorted by the most recent news entry. You can then simply get to the news by using KVC.

To use now the NSFetchedResultsController, you simply replace the lase block where the fetch is executed and saved into an array by this block of code:

NSFetchedResultsController *controller = [[NSFetchedResultsController alloc] 
initWithFetchRequest:allDepartements
managedObjectContext:moc 
sectionNameKeyPath:nil 
cacheName:@"<#Cache name#>"];
    [allDepartementsRelease];

The rest should then work as expected. I have never user NSFetchedResultsController before, I used to code it manually on the mac.

GorillaPatch
I am not so sure anymore if the sortDescriptor works. What do you think of fetching the news directly instead?
GorillaPatch
+1  A: 

Your request does not make sense. Because a department has more than one department news object you can't sort by all of them. You could set up a sort by one of them but you would need to determine which one.

So first define which one of those news items you want to sort by and then you can build the rest.

Marcus S. Zarra