问题
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