How can I set a TableView's titleForHeaderInSection and numberOfRowsInSection with an NSDictionary of NSArrays?

StackOverflow https://stackoverflow.com/questions/23276578

Question

I have an NSDictionary with NSArrays of names, so naturally there are 26 arrays total. I'd like to set the titleForHeaderInSection (A, B, C, etc) with the keys of the arrays and the numberOfRowsInSection with the count of the arrays. I can get the count of each array by enumerating over them with a block, but how can I set these two options on my TableView based on the NSDictionary I have? And is there any way to order the NSDictionary so the results are alphabetical?

Here's the NSDictionary I have:

@{
    @"A" :  
        @[@"Person One", @"Person Two", @"Person Three"],
    @"B" :
        @[@"Person One", @"Person Two", @"Person Three", @"Person Four"],
    @"C" :
        @[@"Person One", @"Person Two"],
}
// etc

Here's the NSLog of the NSDictionary: will the titles be unordered?

A -- 23
B -- 78
G => 27
U => 1
H => 57
V => 6
I => 1
// etc
Was it helpful?

Solution

The entries in a dictionary are not ordered. What you can do is create an array of all the section titles and sort that alphabetically:

NSDictionary *dict = ...; // your dictionary
NSArray *sectionTitles = [[dict allKeys] sortedArrayUsingSelector:@selector(compare:)];

Then the number of sections is

[sectionTitles count]

For a given section number, the title and number of rows can be computed as

NSString *title = sectionTitles[section];
NSUInteger numRows = [dict[sectionTitles[section]] count];

Finally, for a given index path, the corresponding item is

NSString *item = dict[sectionTitles[indexPath.section]][indexPath.row];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top