AppyMike
AppyMike

Reputation: 2064

Custom NSSortDescriptors

I have an NSFetchedResultsController which I use to fetch my core data and populate a table.

To sort the data currently I am using the code below:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"month" ascending:YES];
NSArray *sortDescriptors = @[sortDescriptor];

[fetchRequest setSortDescriptors:sortDescriptors];

month is a NSString of the months of the year and so this currently sorts the months of the year alphabetically.

But what I would like to happen is for the months to be shown in order of closest to todays date.

For example if todays month was April, April would be showed at the top followed by May, June, July etc.

Any help is appreciated, Thanks!

Upvotes: 2

Views: 1038

Answers (1)

Daij-Djan
Daij-Djan

Reputation: 50089

Custom descriptors aren't hard but I don't think a custom SortDescriptor is usable in your case (core data sort descriptors can't run custom code AFAIK)


anyways:

toimplement the descriptor passing it a custom comparator block that returns how the obj1 and obj2 are related to each other

sample code:

id desc = [[NSSortDescriptor alloc] initWithKey:@"month" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
    ...
}];

retval:

typedef NS_ENUM(NSInteger, NSComparisonResult) {NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending};

Upvotes: 1

Related Questions