Search code examples
iosswiftuitableviewnsfetchedresultscontroller

NSFetchedResultsController section number is 0


I have the following hierarchy of entities enter image description here

In my TableViewController i have the following code:

private lazy var fetchedResultsController: NSFetchedResultsController = {
    let fetchRequest = NSFetchRequest(entityName: "Worker")
    let workerTypeSortDescriptor = NSSortDescriptor(key: "workerType", ascending: true)
    let firstNameSortDescriptor = NSSortDescriptor(key: "firstName", ascending: true)

    fetchRequest.sortDescriptors = [workerTypeSortDescriptor,  firstNameSortDescriptor]
    guard let stack = CoreDataStackSingleton.sharedInstance.coreDataStack else {return NSFetchedResultsController()}
    let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: stack.mainQueueContext, sectionNameKeyPath: "workerType", cacheName: nil)
    frc.delegate = self
    return frc
}()
...
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    if let sections = fetchedResultsController.sections {
        print(sections.count)
        return sections.count
    }
    return 0
}
...
func viewDidLoad(){
    ...
    try fetchedResultsController.performFetch()
    ...
}

And i always get the 0 from print(sections.count) i don't know why, because i have 3 entities and i assume to get 3 sections. Here is the project


Solution

  • Assuming you have have your coredata stack working and you have records inserted in the context for each type this should work. But if your context is empty then I would expect the section counts to be 0.