Hi, I have 2 views in a ToDos app, one view allows the user to add new ToDos and mark them as completed and another shows a calendar that allows the user to see all the ToDos that they might have completed on any given day. A many to one relationship exists between the ToDo entity and the DayOfYear entity. When the user taps on the ToDo Complete button I update the completedDay_ relationship under ToDo in Core Data. When I immediately switch to the calendar view FetchRequest doesn't contain anything even though I have context.save() immediately after updating the relationship. But when I restart the app, the calendar view shows the Completed Todo correctly. Am I doing something wrong with FetchRequest?
do {
let today = DayOfYear.withDate(convertStringToDate(day), context: context)
todo.completedDay_ = today
try self.context.save()
} catch {
print("Error saving managed object context: \(error)")
}
extension DayOfYear {
static func withDate(_ day: Date, context: NSManagedObjectContext) -> DayOfYear {
let request = fetchRequest(NSPredicate(format: "date = %@", day 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
}
}
}
@FetchRequest(entity: DayOfYear.entity(), sortDescriptors: [], predicate: NSPredicate(format: "date >= %@ AND date <= %@", Date().startOfMonth() as CVarArg, Date() as CVarArg)) var daysOfYear: FetchedResults<DayOfYear>
Text("Completed ToDos").font(.title)
.onAppear {
print(self.daysOfYear)
// prints empty until I restart the app
}