Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 451
0SX Avatar asked Mar 03 '11 00:03

0SX


2 Answers

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.

like image 84
TechZen Avatar answered Sep 23 '22 07:09

TechZen


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.

like image 26
Dave DeLong Avatar answered Sep 19 '22 07:09

Dave DeLong