Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Core Data NSPredicate – Match Dates

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading