核心数据“,”通过瞬态属性排序“解决方法 [英] Core Data, "sorting by transient property" workaround

查看:143
本文介绍了核心数据“,”通过瞬态属性排序“解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为Event的核心数据实体,它表示重复(每年)事件。每个事件都有一个日期属性。

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

我需要根据下一次发生的日期将此事件呈现给用户。此属性当然取决于当前日期,因此应标记为 transient :将其存储在数据库中没有意义。

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.

但是,正如你所知,你不能通过Core Data中的瞬态属性来查询排序。

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.

推荐答案

如果将日期存储在单独的实体中,那么您可以只获取日期并自己排序,但是您喜欢。你将有一个从Event到EventDate的关系,以及一个相应的反向关系,可以从给定的EventDate中找到Event。

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.

设置EventDate-> Event多对多关系,因为可能发生多个事件落在同一日期。像这样设置你的模型给你很好的属性,你可以很容易地回答问题什么事件发生在X日期?

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

这篇关于核心数据“,”通过瞬态属性排序“解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆