问题描述
我想要完成的是:我需要将核心数据条目的数量限制为 50.因此,如果用户输入他们的第 50 个条目,那么应用程序将删除最旧的条目并将新条目添加到栈顶.所以基本上,如果用户从不删除条目并且如果核心数据中有 50 个条目,那么当用户尝试添加新条目时,应用程序将删除最旧的条目并添加用户的新条目.基本上,我正在尝试做一些历史记录,但我不希望用户能够超过 50 个条目,但是我希望他们能够在达到 50 个限制时添加新条目,只需删除最旧的并添加最新的.最简单的方法是什么?我是核心数据的新手,很难理解其中的很多内容.这是我正在使用的代码/示例应用程序.链接到我正在使用的示例应用程序 感谢您的帮助.
What I'm trying to accomplish is the following: I need to limit the amount of core data entries to 50. So if the user enters their 50th entry then the app would delete the oldest entry and add the new entry to the top of the stack. So basically, if the user never deletes entries and if there are 50 entries in core data then, when the user tries to add a new entry, the app would delete the oldest entry and add the user's new entry. Basically, I'm trying to have a history sort of thing but I don't want the user to be able to go past 50 entries however I want them to be able to add new entries when their at the 50 limit by just dropping the oldest one and adding the newest one. What would be the easiest way to do this? I'm new to core data and having a hard time understanding a lot of it. Here's the code / example app that I'm working with. LINK TO EXAMPLE APP THAT I'M USING Thanks for the help.
推荐答案
假设您有一个名为 History
的实体.最简单的解决方案是将 creationDate
属性添加到您的实体.然后使用它来管理您的 History
对象.
Let's say you have an entity called History
. The easiest solution would be to add a creationDate
attribute to your entities. Then use that to manage your History
objects.
您将需要三个提取:
- 第一个将获取所有现有
History
对象作为故障,然后对它们进行计数.如果计数小于 50,则只需添加新的History
对象即可. - 如果计数>=50,则执行 获取特定值 并使用 @max 或 @min(我忘记了哪个日期)集合运算符来查找最旧的
creationDate
.(幸运的是,链接中的示例几乎正是您所需要的.) - 使用 (2) 返回的
creationDate
对对象执行提取并删除它.
- The first one will fetch as faults all the existing
History
objects and then count them. If the count is <50, then just add the newHistory
object and your done. - If the count>=50, then do a fetch for specific value and use the @max or @min (I forget which for dates) collections operator to find the oldest
creationDate
. (As luck would have it the example at the link it pretty much exactly what you need.) - Perform a fetch for the object with the
creationDate
returned by (2) and delete it.
然后添加新的历史对象.
Then add the new history object.
这篇关于达到 50 个条目限制时如何自动删除最旧的核心数据条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!