I store NSObject
(person) in NSMutableArray
(self.tableData).
I would like to use section like in Address contact : sort alphabetically every fullName in my NSMutableArray
(already done), and access it with index on the right "A,B,C,D..."
I have to get the first letter of person.fullName
, but I don't succeed to loop it.
Maybe I have to use substringWithRange
or subStringToIndex
? I don't really understand the difference.
Here is my code :
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableData = [[NSMutableArray alloc] init];
self.contactSectionTitles = [[NSArray alloc] init];
self.contactIndexTitles = @[@"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"];
[self getPersonOutOfAddressBook];
// Dictionary will hold our sub-arrays
self.dicoAlphabet = [NSMutableDictionary dictionary];
// Iterate over all the values in our sorted array
for (Person *person in self.tableData) {
// Get the first letter and its associated array from the dictionary.
// If the dictionary does not exist create one and associate it with the letter.
NSString *firstLetter = [person.fullName substringToIndex:1];
NSMutableArray *arrayForLetter = [self.dicoAlphabet objectForKey:firstLetter];
if (arrayForLetter == nil) {
arrayForLetter = [NSMutableArray array];
[self.dicoAlphabet setObject:arrayForLetter forKey:firstLetter];
}
// Add the value to the array for this letter
[arrayForLetter addObject:person];
}
// arraysByLetter will contain the result you expect
self.contactSectionTitles = [[self.dicoAlphabet allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
}
cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.accessoryType = UITableViewCellAccessoryNone;
Person *person = [self.tableData objectAtIndex:indexPath.row];
// cell.textLabel.text = person.fullName;
NSString *sectionTitle = [self.contactSectionTitles objectAtIndex:indexPath.section];
NSArray *sectionPerson = [self.dicoAlphabet objectForKey:sectionTitle];
NSString *fullName = [sectionPerson objectAtIndex:indexPath.row];
cell.textLabel.text = fullName;
cell.detailTextLabel.text = person.mainNumber;
}