1
votes

I'm fairly new to ioS dev so this might be obvious.

With Core Data, I have an Entity : 'Post' , with an attribute for "dateAdded".

When the user selects an NSDate on a calendar- I want to fetch all the entries on that day only and load that into a table.

I was thinking of using a predicate where dateAdded (NSDate) would be equal to the calendarSelectedNSDate. But I don't think that would work as their NSDates would be different because of different times.

I would really appreciate a solution! Thank you!

1
You are thinking in right direction. You have to keep the date format same. So while you are storing the date in coreData you would be knowing the format or you change the format accordingly. Now when user selects the date first convert the date into required format and use your predicate.Arun Gupta

1 Answers

3
votes

Use (NS)Calendar to calculate the start and end of the selected date and create a predicate:

// get the current calendar
let calendar = Calendar.current
// get the start of the day of the selected date
let startDate = calendar.startOfDay(for: calendarSelectedNSDate)
// get the start of the day after the selected date
let endDate = calendar.date(byAdding: .day, value: 1, to: startDate, options: .matchNextTime)!
// create a predicate to filter between start date and end date
let predicate = NSPredicate(format: "dateAdded >= %@ AND dateAdded < %@", startDate as NSDate, endDate as NSDate)