-1

I have an entity in core data that stores a Date property date. I have an @State property in my View selectedDate that is of type Date.

I want to use a fetch request to retrieve all of the entities in the database with a date matching selectedDate. I want to do this exclusive of the time; for example selectedDate could be 15/03/2022 at 12:07pm, and date could be 15/03/2022 at 9:05am - I would like these to be matched.

I have tried to use the following (although this will not achieve the desired time behaviour):

request.predicate = NSPredicate(format: "date == %@", selectedDate.timeIntervalSince1970)

However, when running the app I get the following error, on the predicate line:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x41d88c207fdc4b4d)

Does anyone know how to do this?

Jr795
  • 691
  • 1
  • 8
  • 15
  • `selectedDate.timeIntervalSince1970` => `selectedDate` to fix the crash. Concerning your issue, you could use two dates: `startOfTheDayOfSelectedDate` & `endOfTheDayOfSelectedDate`, then, the predicate would be `NSPredicate(format: "date >= %@ && date <= %@", argumentArray: [startOfTheDayOfSelectedDate, endOfTheDayOfSelectedDate])` – Larme Mar 15 '22 at 12:18
  • Does this answer your question? [NSPredicate: filtering objects by day of NSDate property](https://stackoverflow.com/questions/1965331/nspredicate-filtering-objects-by-day-of-nsdate-property) – Willeke Mar 15 '22 at 17:11
  • Or [Core Data Predicate Filter By Today's Date](https://stackoverflow.com/questions/40312105/core-data-predicate-filter-by-todays-date) – Willeke Mar 15 '22 at 17:12

1 Answers1

3

First of all the exception occurs because the placeholder %@ is wrong. %@ is for objects, a Double value is represented by %f.

Second of all if you want to fetch all dates which are in a specific day you have to create a date range (0:00–23:59) of that day.

Using Calendar you get 0:00 with startOfDay(for:) and the end of the day by adding a day and the < operator.

For example

let calendar = Calendar.current
let startDate = calendar.startOfDay(for: selectedDate)
let endDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
let predicate = NSPredicate(format: "date >= %@ AND date < %@", argumentArray: [startDate, endDate]))
vadian
  • 274,689
  • 30
  • 353
  • 361