ios - 使用 NSFetchedResultsController 时如何在每个部分获取一条记录

标签 ios uitableview core-data nsfetchedresultscontroller nsfetchrequest

我正在开发一个使用 Core Data 的 iOS 应用程序,并且我想使用 UITableView 显示一个实体。

为此,我使用 NSFetchedResultsController。 我想要实现的目标是在其部分中显示每条记录。基本上我想要每个部分 1 行。

我正在努力解决的方法是:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

因为我想在计算numberOfSectionsInTableView时有这段代码:

{
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

并且我希望在计算 numberOfRowsInSection 时返回 1(显然我无法将 indexPath.section 传递给 numberOfSectionsInTableView)。 这个问题/情况下的方法是什么?谢谢。

最佳答案

嗯,

显然,您将拥有与对象一样多的部分:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return self.fetchedResultController.fetchedObjects.count;
}

那么,你将只有一行/一节,因为这就是你想要的

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   return 1;
}

然后在 cellForRowAtIndexPath 中使用 indexPath.section 作为 rowIndex,使用 indexPath.row 作为 sectionIndex。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath * correctedIP = [NSIndexPath indexPathForRow:indexPath.section inSection:0];

    id myItem =  [self.fetchedResultController objectAtIndexPath: correctedIP];
/* ... */

}

关于ios - 使用 NSFetchedResultsController 时如何在每个部分获取一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26908107/

相关文章:

ios - UITableView 无法识别 NumberOfRowsInSection

ios - 具有默认协议(protocol)实现的 Swift 枚举

ios - 禁用 WKWebView 打开链接以重定向到我的 iPhone 上安装的应用程序

iphone - 如果设备有 Facebook App,Facebook API 不调用委托(delegate)(请求)方法

IOS如何更新UITableViewCell

arrays - 将自定义数组保存到 Core Data 中

ios - 这将是使用 Core Data (iOS) 更新用户 ReadOnly 数据库的最佳方式

ios - 字符串比较不适用于 Swift

iphone - 如何在 iphone 应用程序的搜索表中显示第一个词

ios - 如何在不创建 *Cell.swift 文件的情况下访问 UITableViewCell 对象