您的位置:首页 > 产品设计 > UI/UE

如何结合CoreData给UITableView的section填充数据

2013-03-28 17:23 691 查看
搬运自StackOverFlow:numberOfRowsInSection: method for core data and multiple sections

问题描述:一个tableview中建立两个section,第一个section使用NSArray填充数据,第二个section使用coredata填充数据

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0) {
return 1;
} else {
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
}

最开始的代码返回错误
Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

解决方法:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0) {
return 1;
} else {
NSUInteger frcSection = section - 1;
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:frcSection];
return [sectionInfo numberOfObjects];
}
}

原因解释:
coredata中的fetched results controller只有一个section(section #0),但我们却想在第二个section(section
#1)里面显示FRC所取得的数据

在cellforrow这个方法里也要对section的数字减一

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0) {
cell.textLabel.text = entityOne.name; //entityOne object passed from previous VC
} else {
NSIndexPath *frcIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:(indexPath.section - 1)];
entityTwo = [self.fetchedResultsController objectAtIndexPath:frcIndexPath];
cell.textLabel.text = entityTwo.name;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  UITableView CoreData