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.
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:
History
objects and then count them. If the count is <50, then just add the new History
object and your done. creationDate
. (As luck would have it the example at the link it pretty much exactly what you need.) creationDate
returned by (2) and delete it. Then add the new history object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With