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
?
Use two fetchedResultsControllers
, say fruitFRC
and drinksFRC
, and then map the indexPath
reported by those FRCs to the indexPath
used by the tableView. For example, if fruit are to appear in section 0 of the tableView, you can just use the tableView indexPath
to lookup in the fruitFRC
to get the fruit details. But for drinks, in section 1 of the tableView, you need to create a new indexPath
since the drinksFRC
will be using section 0. (You can use indexPathForRow:inSection:
method of NSIndexPath
to create the new indexPath.)
Likewise, in numberOfRowsInSection
, if the section
is 0, return the number of objects in fruitFRC
, and if the section
is 1, return the number of objects in drinksFRC
.
And so on...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.