How to automatically delete oldest core data entries when reach 50 entry limit?

六眼飞鱼酱① 提交于 2020-01-10 19:44:11

问题


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.


回答1:


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.

You will need three fetches:

  1. 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 new History object and your done.
  2. 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.)
  3. Perform a fetch for the object with the creationDate returned by (2) and delete it.

Then add the new history object.




回答2:


OK, that's fine. CoreData is not going to do this for you, but you can do it yourself.

You can retrieve objects from you context using an NSFetchRequest, and you can delete them using -[NSManagedObjectContext deleteObject:]. You can sort them using NSSortDescriptor objects.



来源:https://stackoverflow.com/questions/5175255/how-to-automatically-delete-oldest-core-data-entries-when-reach-50-entry-limit

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