Olex
Olex

Reputation: 1656

Grouped UITableView with fetchedResultsController

I had a grouped tableView with 1 section, cell's content was supplied by fetchedResultsController. Now I need to modify this tableview a little. I need to add one UITableviewCell with it's own custom content (independent from fetchedResultsController) as single only for first section. Section two must be same as previous version of this tableView was. So just adding one cell in one section before all existing content. Related methods:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
   // return [[self.fetchedResultsController sections]count];
    return 2;
}

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

but I am having SIGABRT here and -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'. fetchedResultsController retrives data fine, and it is not empty, so what is wrong here?

Upvotes: 2

Views: 200

Answers (1)

Martin R
Martin R

Reputation: 539795

The reason is that section #1 in the table view is section #0 for the fetched results controller. So you have to adjust the section number in numberOfRowsInSection:

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

Note that similar adjustments are necessary

  • in cellForRowAtIndexPath,
  • in the fetched results controller delegate methods

to map between the FRC index path and its corresponding table view index path.

I would write your first method as

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return  1 + [[self.fetchedResultsController sections] count];
}

so that it works even if the FRC has no sections or more than 1 section.

Upvotes: 2

Related Questions