views:

54

answers:

1

I'm developing for iPhone iOS 4.0 and I have a list of birthday objects (date + name) stored using Core Data. I want to use the NSFetchedResultsController to retrieve this list sorted by the next birthdate date of each birthday object. For that I need to define my own logic for the sort descriptor.

I tried using:

[NSSortDescriptor sortDescriptorWithKey:@"birthdayDate" 
                              ascending:YES 
                               selector:@selector(compareNextBirthday:)];

Where compareNextBirthday: is defined in a category I created on a NSDate class.

But when I try to fetch the data I get the following error: "unsupported NSSortDescriptor selector: compareNextBirthday:"

I spent hours trying to figure this out without luck... does Core Data support this kind of custom sorting at all? Do I really need to do an in-memory sort?

+1  A: 

Sorting inside of the NSFetchedResultsController is performed at the persistent store level so if you are using SQLite as the backend it will fail.

For something like this I would de-normalize the data and store the month and day of month in addition to the actual birthdate so that you can sort on them.

Marcus S. Zarra
Given month and day of month fields, how would an NSSortDescriptor look that gives an ordering starting with today and ending with yesterday? I don't see an obvious solution.
Seamus Campbell
There is no way to sort at the persistent store level like that. You would need to pull them into memory to that type of logic. You can filter by de-normalizing the data.
Marcus S. Zarra
But that's exactly what the question is about, is it not? I don't see how denormalizing helps the poster out here.
Seamus Campbell
The question was "why doesn't this work" and it was answered. Sorting by the next birthdate can be accomplished by de-normalizing the data because it removes the year from the equation. Based on his application needs he can explore from there.
Marcus S. Zarra
Thanks for the answer - the question was if custom sorting using selector on categories is supported in core data - and it seems i got the answer which is not. However the alternative solution was not valid. Eventually what i did is to compute the next birthday date before the NSFetchedREsultsController fetch, save it to the object in the store and use this property to sort. I found it more efficient than sorting it in-memory.
Amir Naor
Then please accept the answer, it will improve your reputation on the site.
Marcus S. Zarra