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

来源:互联网 发布:数据监控系统 编辑:程序博客网 时间:2024/06/08 05:59

搬运自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;    }}




原创粉丝点击