Search code examples
ioscore-datansfetchedresultscontroller

How to restrict FetchedResultsController to objects in a given day


I am trying to create a UITableView that populates with objects for a selected date (specifically yesterday, today, and tomorrow) . In my CoreData model, the entity in question as a property date with typeDate`.

To get yesterday, today, and tomorrow I do this (as prescribed by this WWDC session):

var today = Date()
var yesterday = calendar.date(byAdding: .day, value: -1, to: self.date)
var tomorrow = calendar.date(byAdding: .day, value: 1, to: self.date)

and perform:

today = calendar.startOfDay(for: today)
yesterday = calendar.startOfDay(for: yesterday)
tomorrow = calendar.startOfDay(for: tomorrow)

Once I get all of the dates, I don't know what to do. Currently my fetched results controller looks like:

    lazy var fetchedResultsController: NSFetchedResultsController<Entry> = {

        let fetchRequest: NSFetchRequest<Entry> = Entry.fetchRequest()

        // Configure Fetch Request
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]

        // Create Fetched Results Controller
        let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: app_delegate.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)

        // Configure Fetched Results Controller
        fetchedResultsController.delegate = self

        return fetchedResultsController
}()

How do I restrict the fetchedResultsController to one of those dates and, if possible, I do I do it using Calendars method: isDateInToday()?


Solution

  • Add a predicate to the fetch request.

    request.predicate = NSPredicate(format: "date > %@ && date < %@", 
       today as NSDate, tomorrow as NSDate)