我有一个带有两个 UITableViews
的 UIViewController
。这两个表是从不同的实体填充的,因此我使用了两个获取的结果 Controller 。在使用 UITableViewDelegate/Datasource 方法时,我该如何指定使用哪个 fetchedResultsController
?
How to filter NSFetchedResultsController (CoreData) with UISearchDisplayController/UISearchBar
上面的链接基本上介绍了如何实现两个 FRC,但我是新手,所以我不确定他下面的方法是如何工作的。
- (NSFetchedResultsController *)fetchedResultsControllerForTableView:(UITableView *)tableView
{
return tableView == self.tableView ? self.fetchedResultsController : self.searchFetchedResultsController;
}
谁能帮我解释一下?特别是 return tableView == ....
行。
提前致谢!
最佳答案
这里您可能需要了解两件事。
首先,该语句包含一个三元运算符('?')。三元运算符是为了方便编程,那一行完全一样:
if(tableView == self.tableView){
return self.fetchedResultsController;
} else {
return self.searchFetchedResultsController;
}
第二件事是理解回调。您在 UIViewController 中控制两个 tableView,它们各自使用自己的 NSFetchedResultsController。当系统调用 fetchedResultsControllerForTableView 回调时,您必须为给定的表返回正确的 fetchedResultsController。
所以 fetchedResultsControllerForTablView 函数通常看起来像这样:
- (NSFetchedResultsController *)fetchedResultsControllerForTableView:(UITableView *)tableView
{
if(tableView == self.tableView1){
return self.fetchedResultsController1;
} else if (tableView == self.tableView2){
return self.fetchedResultsController2;
} else if ...
对于 n 个表。
编辑: 这个函数不是系统调用的,而是在用户类中调用的辅助方法。 (我只是重新阅读了问题中的链接)。但是这个想法本质上是一样的。
让我们以 numberOfSectionsInTableView 函数为例。这是由 iOS 系统调用的,以便它知道要在 tableView 中放置多少个部分。系统将有问题的 TableView 传递给函数。好吧,sections 的数量是根据 fetchedResultsController 中的信息来确定的,但是我们使用哪个 fetchedResultsController 呢?辅助函数获取表格(最初传递给 numberOfSectionsInTableView 函数)并找出要使用的 fetchedResultsController。然后我们用它来回答“有多少部分?”这个问题
关于ios - 使用多个时如何使用正确的 fetchedResultsController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18769772/