Skip to content

Instantly share code, notes, and snippets.

@MaisaMilena
Created September 15, 2023 23:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaisaMilena/36a157bbeda11cbf50db30feb1213be4 to your computer and use it in GitHub Desktop.
Save MaisaMilena/36a157bbeda11cbf50db30feb1213be4 to your computer and use it in GitHub Desktop.

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)
}

Example:
image

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) {
    ...
}
@MaisaMilena
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment