I can fetch one entity and display the data in a tableview with single section using NSFetchedResultsController
. But how to fetch two or more entities (no relation) using NSFetchedResultsController
and display the data in different section?
I noticed that using core data, I can get number of section and number of row using NSFetchedResultsController
. I set one entity in NSFetchedResultsController
and it handles tableView
very well including add and delete row.
func getFetchedResultController() - > NSFetchedResultsController {
fetchedResultController = NSFetchedResultsController(fetchRequest: fetchRequest(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultController.delegate = self
fetchedResultController.performFetch(nil)
return fetchedResultController
}
func fetchRequest() - > NSFetchRequest {
let fetchRequest = NSFetchRequest(entityName: "Fruits")
let sortDescriptor = NSSortDescriptor(key: "desc", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
return fetchRequest
}
override func numberOfSectionsInTableView(tableView: UITableView) - > Int {
let section = fetchedResultController.sections ? .count
return section!
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) - > Int {
if let s = fetchedResultController.sections as ? [NSFetchedResultsSectionInfo] {
return s[section].numberOfObjects
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) - > UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let fruit = fetchedResultController.objectAtIndexPath(indexPath) as Fruits
cell.textLabel.text = fruit.desc
return cell
}
But section always zero because it only uses one entity. Let say I want to show 2 entities/tables Fruits and Drinks (no relation), where should I put these entities in my code above? Can NSFetchedResultsController
handles these entities in different section in tableView
?