Reputation: 766
I'm displaying a dynamic list of names in a table view, and I'm trying to split them into sections according to the first letter of the name...
I've created an array with an alphabetical list of letters
charIndex = [[NSMutableArray alloc] init];
for(int i=0; i<[appDelegate.children count]-1; i++)
{
// get the person
Child *aChild = [appDelegate.children objectAtIndex:i];
// get the first letter of the first name
NSString *firstLetter = [aChild.firstName substringToIndex:1];
NSLog(@"first letter: %@", firstLetter);
// if the index doesn't contain the letter
if(![charIndex containsObject:firstLetter])
{
// then add it to the index
NSLog(@"adding: %@", firstLetter);
[charIndex addObject:firstLetter];
}
}
and I've set up the number of sections and title
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// set the number of sections in the table to match the number of first letters
return [charIndex count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
// set the section title to the matching letter
return [charIndex objectAtIndex:section];
}
But I'm having trouble with what should be in
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
}
Upvotes: 2
Views: 4461
Reputation: 6042
You could add a dictionary that keeps track of the number of people that share the same first letter. Quick untested code:
charIndex = [[NSMutableArray alloc] init];
charCount = [[NSMutableDictionary alloc] init];
for(int i=0; i<[appDelegate.children count]-1; i++)
{
// get the person
Child *aChild = [appDelegate.children objectAtIndex:i];
// get the first letter of the first name
NSString *firstLetter = [aChild.firstName substringToIndex:1];
NSLog(@"first letter: %@", firstLetter);
// if the index doesn't contain the letter
if(![charIndex containsObject:firstLetter])
{
// then add it to the index
NSLog(@"adding: %@", firstLetter);
[charIndex addObject:firstLetter];
[charCount setObject:[NSNumber numberWithInt:1] forKey:firstLetter];
}
[charCount setObject:[NSNumber numberWithInt:[[charCount objectForKey:firstLetter] intValue] + 1] forKey:firstLetter];
}
Then in:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
[charCount objectForKey:[charIndex objectAtIndex:section]];
}
Upvotes: 4