flohei
flohei

Reputation: 5308

Add a custom section to UITableView when working with NSFetchedResultsController

I'm working with NSFetchedResultsController to fill one of my UITableViews with data grouped into sections. Now I want to add a new section atop all the fetched sections created by data that would not be fetched (I'm creating an additional array for that). Is there a nice way to insert that array without breaking all the nice NSFetchedResultsController behavior?

Update

What I've tried so far is to manually adjust every use of the indexPath. When ever a method (i.e. -tableView:numbersOfRowsInSection) get's called I check if it's the first section and if so I would take the data from my array instead of the NSFetchedResultsController. If not, I would just create a new NSIndexPath with the original indexPath's row and the section - 1 to access the fetchedResults. This seems to be a rather naive approach. At least, this does not work for me (yet).

Thanks!
–f

Upvotes: 1

Views: 1076

Answers (1)

Christian Beer
Christian Beer

Reputation: 2025

I created a UITableViewDataSource with a mixture of static and dynamic sections. I do it by modifying NSIndexPath like you planned. Important is to modify the NSIndexPath in the delegate methods of NSFetchedResultsControllerDelegate, too:

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath
{
    indexPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:kSectionWithAdditionalRowIndex];
    if (newIndexPath) {
        newIndexPath = [NSIndexPath indexPathForRow:newIndexPath.row + 1 inSection:kSectionWithAdditionalRowIndex];
    }

    [super controller:controller didChangeObject:anObject atIndexPath:indexPath forChangeType:type newIndexPath:newIndexPath];
}

The sample is taken from a subclass of my class CBUIFetchResultsDataSource.m, which is a generic UITableViewDataSource powered by a NSFetchedResultsController. I had to also overwrite -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section, -(id)objectAtIndexPath:(NSIndexPath*)indexPath and -(NSIndexPath*)indexPathForObject:(id)object.

Upvotes: 3

Related Questions