I am on my way with creating a habit tracking app which uses Core Data for storing the habits. Because I need to know when I completed a part of my habit, I created a different entity containing only a Date with a many to one relationship to the habit entity. So one habit has a reference to many different dates on which it was completed, and the other way around.
First question: Is this the best method for doing this? Because the longer someone uses the app the more cluttered it gets with dates.
Second question: If it is good, how do I count the times I completed some habit for one specific date or a specific time interval (eg. week). I currently just compactMap over an array and count the result, but when having around 150 items in this array, it gets rather slow:
withAnimation(.easeInOut) {
let todayCount = habit.dateArray.compactMap { (Calendar.current.isDateInToday($0.date!)) }
return todayCount.count
}
I currently add a Date like this:
let newhabit = HabitCompletionDate(context: viewContext)
newhabit.date = Date()
newhabit.item = habit
And delete like this:
let habitObject = habit.date?.allObjects.last
viewContext.delete(habitObject as! NSManagedObject)
I don´t need the specific time, only the day of completion would still be enough, but this was the only solution I could come up with.
I have seen someone saying that you could do something like this with an NSPredicate but I did not understand how. As you might have guessed by this rather basic questions, I have no real experience in Core Data and personally it often gives me headaches.
Thanks in advance!