software-mariodiana
6/7/2014 - 7:08 PM

How to use a UILocalizedIndexCollation to create a table with sections.

How to use a UILocalizedIndexCollation to create a table with sections.

/*
 * Assume the following: 
 * 
 *   @property UILocalizedIndexCollation *collation;
 *   @property NSMutableArray *sections;
 *   @property NSArray *tableData;
 */

- (void)configureSectionData
{
    // We need an array of arrays: inner arrays comprise names starting with specific letter.
    NSUInteger sectionTitlesCount = [[[self collation] sectionTitles] count];
    self.sections = [NSMutableArray arrayWithCapacity:sectionTitlesCount];
    
    // The outer array (sections) will hold a mutable array (sectionData) for each section.
    for (int i = 0; i < sectionTitlesCount; i++) {
        [[self sections] addObject:[NSMutableArray array]];
    }
    
    // Insert name in the inner array corresponding to its first letter.
    for (id aName in self.tableData) {
        NSInteger sectionNumber = [[self collation] sectionForObject:aName
                                             collationStringSelector:@selector(lowercaseString)];
        
        NSMutableArray *sectionNames = [[self sections] objectAtIndex:sectionNumber];
        [sectionNames addObject:aName];
    }
    
    // Sort each inner array.
    for (int i = 0; i < sectionTitlesCount; i++) {
        NSMutableArray *names = [[self sections] objectAtIndex:i];
        NSArray *sortedNames = [[self collation] sortedArrayFromArray:names
                                              collationStringSelector:@selector(lowercaseString)];
        
        [[self sections] replaceObjectAtIndex:i withObject:sortedNames];
    }
}