ios - 核心数据 : Fetch Multiple Entities using NSFetchedResultController

标签 ios objective-c core-data swift nsfetchedresultscontroller

我可以使用 NSFetchedResultsController 获取一个实体并在具有单个部分的 TableView 中显示数据。但是如何使用 NSFetchedResultsController 获取两个或多个实体(无关系)并在不同部分显示数据?

我注意到使用核心数据,我可以使用 NSFetchedResultsController 获取节数和行数。我在 NSFetchedResultsController 中设置了一个实体,它可以很好地处理 tableView,包括添加和删除行。

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
}

但部分始终为零,因为它只使用一个实体。假设我想显示 2 个实体/表格 Fruits 和 Drinks(无关系),我应该将这些实体放在上面的代码中的什么位置? NSFetchedResultsController 能否在 tableView 的不同部分处理这些实体?

最佳答案

使用两个 fetchedResultsControllers,比如fruitFRCdrinksFRC,然后映射indexPath 由这些 FRC 报告给 tableView 使用的 indexPath。例如,如果水果要出现在 tableView 的第 0 部分,您可以只使用 tableView indexPathfruitFRC 中查找以获得水果详细信息。但是对于饮料,在 tableView 的第 1 部分中,您需要创建一个新的 indexPath,因为 drinksFRC 将使用第 0 部分。(您可以使用 indexPathForRow: inSection: NSIndexPath 的方法来创建新的 indexPath。)

同样,在numberOfRowsInSection中,如果section为0,则返回fruitFRC中的对象数,如果section 为1,返回drinksFRC中对象的个数。

等等……

关于ios - 核心数据 : Fetch Multiple Entities using NSFetchedResultController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27056418/

相关文章:

ios - 谁能弄清楚如何手动触发这个饼图(XYPieChart)的动画?

iphone - 申请因未遵循 iOS 数据存储指南而被拒绝

ios - didFinishLaunchingWithOptions 调用了两次

swift - 在一个或两个表已经保存后,如何加快表之间的更新关系?

c++ - 在不同平台上从 stringstream 解析数字时的行为不一致

ios - 状态栏由于某种原因变成黑色

ios - 重复的接口(interface)定义和预期的选择器错误

ios - 在模拟器中更改 ios 版本后,组件在 ViewController 中的位置错误

objective-c - 在启用 ARC 的情况下更新属性

objective-c - FilteredArrayUsingPredicate 总是返回 nil NSArray?