Core Data, "sorting by transient property" workaround
Asked Answered
B

1

12

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.

Bathurst answered 5/5, 2011 at 3:45 Comment(1)
You either fetch, calculate and sort it yourself, or store it and let Core Data sort.Fahrenheit
C
5

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?"

Cardie answered 5/5, 2011 at 4:4 Comment(4)
How can I make Core Data sort some dates "from the beginning of the year"? To my understanding it only sorts dates, i.e. taking the year into account.Bathurst
To answer myself: I think I'll split the NSDate into day, month and year fields and sort them with 2 sort descriptors.Bathurst
That's one way to do it. Another is to just use the same year for all your events. Since the events are apparently understood to repeat annually, you're probably ignoring the year in actual use anyway.Cardie
+1 Dates are deceptively complex to deal with. You often find yourself having to create fairly detailed models to handle them.Scraggy

© 2022 - 2024 — McMap. All rights reserved.