I have an object called Delivery
that has a set of Customer
objects associated with it. Each Delivery object also stores a mainCustomerId
which is an NSNumber*
. I have an NSFetchedResultsController that is used to manage the datasource for a UITableView
. The issue is that I want to sort the NSFetchedResultsController by the Customer's lastName field (the customer again is stored in a many-to-many relationship called customers
on the Delivery
object) where one of the customers in the set has a customerId equal to the Delivery's MainCustomerId.
The Delivery Class Looks like this (only the relevant parts)
@interface Delivery : NSManagedObject
@property (nonatomic, retain) NSNumber * mainCustomerId;
@property (nonatomic, retain) NSSet *customers;
@end
The Customer Class Looks like this
@interface Customer : NSManagedObject
@property (nonatomic, retain) NSNumber * customerId;
@property (nonatomic, retain) NSString * lastName;
// And the inverse relationship to the deliveries
@property (nonatomic, retain) NSSet *deliveries;
@end
I need to make an NSSortDescriptor that does something like this (Note, I know this is the wrong format and will not work. I hope it communicates the idea though)
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"customers.AnyobjectInSet.lastName WHERE AnyobjectInSet.customerId == masterCustomerId ascending:YES];
I have tried several things using subqueries and NSExpressions but always come up short since I can't use any features that use Cocoa (like sorting with @selector) because it has to be able to generate a real mysql query with no Cocoa processing of the data. But I feel like there has to be someway to do this since it would be an easy query in mysql.
select * from Delivery JOIN Customer ON Customer.customerId=Delivery.mainCustomerId ORDER BY Customer.lastName;
I am trying to avoid having to sort after the results are fetched and store the sort order back on the object (which would be easy, but I feel it is the wrong solution since I am selecting the relevant data. There has to be a way to sort by it). Any help would be super appreciated.
Thanks in advance.