Core Data, “sorting by transient property” workaround

北慕城南 提交于 2019-12-08 15:27:01

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/5892450/core-data-sorting-by-transient-property-workaround

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!