我正在开发一个使用 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/