I have a table view, which has its data source from an array that contains names of people.
Now to make it easy to find people, I want to section the table view so that it has the letter A-Z on the right hand side, just like the Address Book app.
But my current array just contains a collection of NSStrings. How do I split them so that they are grouped by the first letter of the names? Is there any convenient way to do it?
EDIT: If anyone's interested in my final code:
NSMutableArray *arrayChars = [[NSMutableArray alloc] init];
for (char i = 'A'; i <= 'Z' ; i++) {
    NSMutableDictionary *characterDict = [[NSMutableDictionary alloc]init];
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    for (int k = 0; k < [myList count]; k++) {
        NSString *currentName = [[friends objectAtIndex:k] objectForKey:@"name"];
        char heading = [currentName characterAtIndex:0];
        heading = toupper(heading);
        if (heading == i) {
            [tempArray addObject:[friends objectAtIndex:k]];
        }
    }
    [characterDict setObject:tempArray forKey:@"rowValues"];
    [characterDict setObject:[NSString stringWithFormat:@"%c",i] forKey:@"headerTitle"];
    [arrayChars addObject:characterDict];
    [characterDict release];
    [tempArray release];
}
At the end of the function I'll have:
arrayChars [0] = dictionary(headerTitle = 'A', rowValues = {"adam", "alice", etc})
arrayChars[1] = dictionary(headerTitle = 'B', rowValues = {"Bob", etc})
Thank you everyone for your help!
You can use a dictionary to sort them, so create an array with all the letters you want to sort and a array with nil objects to initialize the dictionary
NSArray *names = @[@"javier",@"juan", @"pedro", @"juan", @"diego"];
NSArray *letters = @[@"j", @"p", @"d"];
NSMutableArray *objects = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < [letters count]; ++i)
{
    [objects addObject:[[NSMutableArray alloc] init]];
}
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjects:objects forKeys:letters];
Then you must find the first letter if the word and put that word into the corresponding key in the dictionary
for (NSString *name in names) {
    NSString *firstLetter = [name substringToIndex:1];
    for (NSString *letter in letters) {
        if ([firstLetter isEqualToString:letter]) {
            NSMutableArray *currentObjects = [dictionary objectForKey:letter];
            [currentObjects addObject:name];
        }
    }
}
To check you can print directly the dictionary
NSLog(@"%@", dictionary);
Then is your work to fill your sections in the tableview using the dictionary
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With