Reputation: 5960
In my core data model, I have a person entity with properties of firstName and lastName. When I use sort descriptors with a fetchedResultsController, I sort by firstName. But if the firstName is nil, I want to use the lastName instead.
I also have a relationship between person and objects, called personOfObjects where person<-->>objects. I am sorting to present in a UITableView. It works fine except for the cases where the first name is nil. In that case they all get grouped into the same group, when these special cases should really be sorted by the last name instead.
Here is what I do now:
NSEntityDescription * entity = [NSEntityDescription entityForName:@"object" inManagedObjectContext:dataInterface.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *personSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"personOfObject.firstName" ascending:YES];
NSSortDescriptor *objectSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"objectDescription" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:personSortDescriptor, objectSortDescriptor, nil];
I thought I could create a helper function in the person class, like this:
- (NSString *) firstLast {
if (![self.firstName isNullString] ) return self.firstName;
if (![self.lastName isNullString] ) return self.lastName;
return @"";
}
and then change the first sort descriptor to refer to this function:
NSSortDescriptor *personSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"personOfObject.firstLast" ascending:YES];
NSSortDescriptor *objectSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"objectDescription" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:personSortDescriptor, objectSortDescriptor, nil];
I didn't really expect this to work (and it didn't), but I am wondering if there is a straightforward way to do something like this.
Upvotes: 1
Views: 1160
Reputation: 6641
You can do this by using your own NSComparator ( How to use NSComparator? )
this question has some code for it, too:
How to Sort an NSMutableArray of Managed Objects through an object graph
You'll have to add your conditional compare in the comparator rather than chaining sort descriptors.
Upvotes: 2