I have two entities in CoreData Todo and DaysOfYear and a many to one relationship exists between these two entities. When the user launches the app if for the past 4 days the user has not completed any of the todos I add those todos to the incompleteTodos relationship for each day. Thing is only the first day gets updated in core data while the rest of them do not update. I have tried everything that I could, all to no avail. Core Data simply refuses to store any of the updates I make except for the first day even though context.hasChanges acknowledges that the context has changed.
ContentView from where I add IncompleteTodos:
Extension Todo:
Extension DayOfYear:
So let's say if I add 4 incompleteTodos for 10th, 9th, 8th and 7th September 2020. Core Data would only update the relationship for 7th September and store 4 incompleteTodos while 8th, 9th, 10th Septmeber will show 0 incompleteTodos after running this code. If I add a new Todo on the 10th, it will immediately be reflected in incompleteTodos for the 10th, but will NOT update incompleteTodos for 11th September.
ContentView from where I add IncompleteTodos:
Code Block Todo.addIncompleteTodo(todo: todo, for: days[idx].date, context: context)
Extension Todo:
Code Block static func addIncompleteTodo(todo: Todo, for day: String, context: NSManagedObjectContext) { let today = DayOfYear.withDate(convertStringToGMTDate(day), context: context) todo.incompleteDay = today today.addToIncompleteTodos_(todo) print(context.hasChanges) try? context.save() }
Extension DayOfYear:
Code Block static func withDate(_ day: Date, context: NSManagedObjectContext) -> DayOfYear { let request = fetchRequest(NSPredicate(format: "date >= %@ AND date <= %@", day.startOfDay() as CVarArg, day.endOfDay() as CVarArg)) let days = (try? context.fetch(request)) ?? [] if let day = days.first { return day } else { let newDay = DayOfYear(context: context) newDay.date = day return newDay } } static func fetchRequest(_ predicate: NSPredicate) -> NSFetchRequest<DayOfYear> { let request = NSFetchRequest<DaysOfYear>(entityName: "DaysOfYear") request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)] request.predicate = predicate return request }
So let's say if I add 4 incompleteTodos for 10th, 9th, 8th and 7th September 2020. Core Data would only update the relationship for 7th September and store 4 incompleteTodos while 8th, 9th, 10th Septmeber will show 0 incompleteTodos after running this code. If I add a new Todo on the 10th, it will immediately be reflected in incompleteTodos for the 10th, but will NOT update incompleteTodos for 11th September.