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

本文介绍如何在一个UITableView中设置两个section,其中一个使用NSArray填充,另一个使用CoreData填充,并解决了因section索引不匹配导致的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值