Custom sorting using categories and core data - is it supported by the framework?
Asked Answered
H

1

5

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?

Higdon answered 11/8, 2010 at 5:30 Comment(0)
B
7

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.

Bandicoot answered 11/8, 2010 at 15:20 Comment(6)
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.Irreversible
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.Bandicoot
But that's exactly what the question is about, is it not? I don't see how denormalizing helps the poster out here.Irreversible
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.Bandicoot
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.Higdon
Then please accept the answer, it will improve your reputation on the site.Bandicoot

© 2022 - 2024 — McMap. All rights reserved.