cannyboy cannyboy - 13 days ago 5x
Objective-C Question

Turning an NSArray of custom objects into a alphabetically sectioned UITableView with an index?

(hmm.. long title)

If I start out with an NSArray of custom objects (each object is a Person) like this:

surname:Allen forename: Woody,
surname:Baxter forename: Stanley,
surname:Clay forename: Cassius


You can see that the array is already in surname order. How do I use that array to create a a UITableView with a section headers A, B C etc, as well as an index thing on the side running vertically



I guess what I'm asking is how to turn my array of objects into a Section Array, with all the first letters of the Surnames, and a Surname Array which is perhaps a nested array like this:

letter: a
{ surname:Allen forename: Woody }
letter: b
{ surname:Baxter forename: Stanley }

In fact, perhaps just a nested array will do.


There are probably a million ways of doing this :) Here's one that might work (I am sure it can be done much prettier, but since no one is answering):

NSMutableDictionary *aIndexDictionary = [[NSMutableDictionary alloc] init]; 
NSMutableArray *currentArray;
NSRange aRange = NSMakeRange(0, 1);
NSString *firstLetter;
for (Person *aPerson in personArray) {
  firstLetter = [aPerson.surname substringWithRange:aRange];
  if ([aIndexDictionary objectForKey:firstLetter] == nil) {
    currentArray = [NSMutableArray array];
    [aIndexDictionary setObject:currentArray forKey:firstLetter];
  [currentArray addObject:aPerson];