Search code examples
ioscore-dataswift3nsfetchedresultscontroller

NSFetchedResultsController does not return any result


I am trying to use NSFetchedResultsController to fetch records from CoreData

I am using the following code:

let fetchedResultsController: NSFetchedResultsController<Appointment> = {
    let fetchRequest = NSFetchRequest<Appointment>(entityName: "Appointment")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
    let moc:NSManagedObjectContext = CoreDataManager.managedObjectContext
    let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil)
    return frc 
}()

And in numberOfItemsInSection delegate I have defined

if let count = fetchedResultsController.sections?[0].numberOfObjects {
    return count
}
return 0

Last in cellForItemAt delegate method, I have defined

let appointment = self.fetchedResultsController.object(at: indexPath)

The issue, is it does not display any records from core data. Nor does it show any error. the list just comes empty.

If I fetch the record using the following code it works.

public func fetchAppointmentList() -> [Appointment] {
    var list:[Appointment] = []
    let request: NSFetchRequest<Appointment> = Appointment.fetchRequest()
    do {
        list = try moc.fetch(request)
    } catch {
        fatalError("\(error)")
    }
    return list
}
override func viewDidLoad() {
    super.viewDidLoad()
    self.appointmentList = self.fetchAppointmentList()
}
// Removed rest of the code to keep it simple.

Why is my fetchedResultsController not working?

Thanks.


Solution

  • Okay, I forgot to call performFetch() in viewDidLoad(), defining the following code in viewDidLoad solved my issue.

    do {
        try fetchedResultsController.performFetch()
    } catch {
        print("An error occurred")
    }