Filtering a Date
attribute for a CoreData Entity can be very confusing. The documentation didn't help me to solve this, but ChatGPT got me into the right track. Here is my solution:
/// Creates a predicate to fetch a `key` attribute in a certain `date`
func makeFetchRequestPredicate(for key: String, on date: Date) -> NSPredicate {
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let currentDay: CVarArg = calendar.date(from: components)! as CVarArg
let nextDay: CVarArg = calendar.date(byAdding: .day, value: 1, to: calendar.date(from: components)!)! as CVarArg
return NSPredicate(format: "\(key) >= %@ && \(key) < %@", currentDay, nextDay)
}
let fetchRequest: NSFetchRequest<MyEntity> = MyEntity.fetchRequest()
fetchRequest.predicate = makeFetchRequestPredicate(for: "startDate", on: date)
let sortDescriptor = NSSortDescriptor(key: "startDate", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
if let result = try? container.viewContext.fetch(fetchRequest) {
...
}
For reference: https://academy.realm.io/posts/nspredicate-cheatsheet/