NSDictionary from the sections and contents of the table

advertisements

Edit: Updated code

I'm trying to create a dictionary from table sections and then the index list within each section, so the section letter would be the key... For the sections I have:

self.collation = [UILocalizedIndexedCollation currentCollation];

NSInteger index, sectionTitlesCount = [[collation sectionTitles] count];

NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];

NSString *alphabet = [[NSString alloc] initWithString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZ"];

for (index = 0; index < sectionTitlesCount; index++) {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [newSectionsArray addObject:array];

    NSString *letter = [alphabet substringWithRange:NSMakeRange(index, 1)];
    [myDict setObject:newSectionsArray forKey:letter];

    [array release];
}

This crashes with:

'*** -[NSCFString substringWithRange:]: Range or index out of bounds'

Then for each letter I need to add the data for that section, I think this array would be the object for the section/letter key:

for (Data *myData in self.dataModel.datalist) {

    NSInteger sectionNumber = [collation sectionForObject:myData collationStringSelector:@selector(myName)];

    NSMutableArray *sectionData = [newSectionsArray objectAtIndex:sectionNumber];

    [sectionData addObject:myData];

}

Hope this makes sense! Thanks!!!


Define your sections in an array

        sections = [NSArray arrayWithObjects:@"#", @"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h", @"i", @"j", @"k", @"l", @"m", @"n", @"o", @"p", @"q", @"r", @"s", @"t", @"u", @"v", @"w", @"x", @"y", @"z", nil];

implement the delegate methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tView {
    return [sections count];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return sections;
}

Then in - (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath { you can get your subsection of the data

NSArray *sectionArray = [myData filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", [sections objectAtIndex:[indexPath section]]]];