objective-cnsfetchedresultscontrolleruilocalizedcollation

NSFetchedResultsController with indexed UITableViewController and UILocalizedIndexedCollation


I have a table that uses an NSFetchedResultsController. This gets me an index with the headers that are present

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [[_fetchedResultsController sections] count];
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [[[_fetchedResultsController sections] objectAtIndex:section] name];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger numberOfRows = 0;
    NSArray *sections = _fetchedResultsController.sections;
    if(sections.count > 0)
    {
        id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:section];
        numberOfRows = [sectionInfo numberOfObjects];
    }
    return numberOfRows;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return [_fetchedResultsController sectionIndexTitles];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return [_fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}

but I want to use UILocalizedIndexCollation to get the complete alphabet.

How do I wire up these methods to the NSFetchedResultsController?

I think I need to get the index titles from the current Collation

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
}

but I am lost on how to write this method

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    //How do I translate index here to be the index of the _fetchedResultsController?
    return [_fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}    

Solution

  • I think you have to traverse the fetched results controller sections and find a matching section for the given title, for example:

    - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
    {
        NSInteger section = 0;
        for (id <NSFetchedResultsSectionInfo> sectionInfo in [_fetchedResultsController sections]) {
            if ([sectionInfo.indexTitle compare:title] >= 0)
                break;
            section++;
        }
        return section;
    }
    

    For section index titles that to not have a matching section, you have to decide if you want to jump to a "lower" or "higher" section. The above method jumps to the next higher section.