Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data, "sorting by transient property" workaround

Let's say I have a Core Data entity called Event, which represents recurrent (yearly) events. Each Event has a "date" property.

I need to present this events to the user sorted by "next occurrence of date". This property, of course, depends on the current date and as such should be marked as transient: there's no point in storing it in the database.

But, as you know, you can't query sorting by a transient property in Core Data.

Is there a smart way to keep this property transient and still have Core Data sort for me? I don't want to fetch and then sort myself, but I would also like to avoid storing this transient info in the database.

like image 766
mips Avatar asked May 05 '11 03:05

mips


1 Answers

If you store the date in a separate entity, then you can fetch just the dates and sort them yourself however you like. You'd have a relationship from Event to EventDate, and a corresponding inverse relationship that lets you find the Event from a given EventDate.

Suggestion: Specify a sort descriptor in your fetch request so that you get the dates sorted from the beginning of the year. Then all you have to do is locate the current date in the returned array, and move everything before that point to the end of the array.

Make the EventDate->Event relationship to-many, since it might happen that more than one Event falls on the same date. Setting your model up like this gives you the nice property that you can easily answer the question "What events happen on date X?"

like image 96
Caleb Avatar answered Oct 12 '22 17:10

Caleb