NSFetchedResultsController section number is 0

自作多情 提交于 2019-12-23 06:14:17

问题


I have the following hierarchy of entities

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


回答1:


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.




回答2:


When creating a frc with groups the first sort descriptor has to be the same key as the group key.

So, create another sort descriptor that sorts by workerType and set that as the first sort descriptor in the array. (The second sort descriptor is the firstNameSortDescriptor).

This should then create the sections that you want.

Also... Are you calling performFetch on the fetched results controller?

You need to call this for the frc to work.



来源:https://stackoverflow.com/questions/35827064/nsfetchedresultscontroller-section-number-is-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!