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

后端 未结 2 1534
不知归路
不知归路 2020-12-31 23:48

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

相关标签:
2条回答
  • 2021-01-01 00:32

    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.

    0 讨论(0)
  • 2021-01-01 00:34

    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.

    0 讨论(0)
提交回复
热议问题