Search code examples
ioscore-datansfetchedresultscontrollernsfetchrequestnssortdescriptor

Core Data - NSFetchedResultController Sort data by other tables field


I have two tables -- master & details -- related to each other (One Master - Many Details)

I want to display list of records from Details table, sorted by "date" field in Master table.

How do I manipulated NSSortDescriptor in following code? OR Any other suggestion for my problem?

Code:

NSFetchRequest *fr = [[NSFetchRequest alloc] init];
NSEntityDescription *e = [NSEntityDescription entityForName:@"Details"
                                     inManagedObjectContext:context];
[fr setEntity:e];

NSSortDescriptor *sd = [[NSSortDescriptor alloc]
                                       initWithKey:@"date" // ---- PROBLEM
                                         ascending:YES];

NSArray *arrSD = [[NSArray alloc] initWithObjects:sd, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

self.frc = [[NSFetchedResultsController alloc]
                         initWithFetchRequest:fr
                         managedObjectContext:context
                           sectionNameKeyPath:nil
                                    cacheName:nil];

NSError *err;
[self.frc performFetch:&err];

Now, I want the data to be sorted with "date" - field, which is column name of Master table.


Solution

  • First you need to set relationships between master and detail tables.

    Then you will be able to use other table filed in your sort description in the next way .. Your relationship name must not be a collection (in one master - many details relationship you will be able to use such field only when you creating sort descriptor for details table)

    And your sort description will look like this:

    NSSortDescriptor *sd = [[NSSortDescriptor alloc]
                                           initWithKey:@"master.date"
                                             ascending:YES];