0

I want to implement something similar to the iPhone's Contact list. I know that there is an address book framework that allows me to access the device's contacts, but I want to use my own contacts stored in my Core Data database.

I am using NSFetchedResultsControllerto fetch and list my contacts on a table view.

However, I can not seem to find a way to get NSFetchedResultsController to display my contacts organized by section, being each section the first letter of each contact's name. Like:

Section A: All contacts that start with the letter A
Section B: All contacts that start with the letter B
etc...

I think that I can do this with the sectionNameKeyPath: parameter in the init method for NSFetchedResultsController, but how am I supposed to use it to achieve my ends?

Tiago Veloso
  • 8,513
  • 17
  • 64
  • 85
  • I have solved my problem following the answers on this question http://stackoverflow.com/questions/1112521/nsfetchedresultscontroller-with-sections-created-by-first-letter-of-a-string – Tiago Veloso May 06 '12 at 16:50

1 Answers1

1

You have to sort your data first and get a list of "keys" (A, B, C, D, E) for each section. Save these as an NSArray on a property.

Implement this:

// Function to load your data
-(void)dataDidLoad
{
// sort the keys
        self.sortedKeysForUsersWithApp = tSortedKeys;
//
        [self.tableView reloadData];
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
// add a UILabel
    headerLabel.text = [self.sortedKeysForUsersWithApp objectAtIndex:section];
// set the text to the section title
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return [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];
}

-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    //return [self.sortedKeys indexOfObject:title];
    return [self.sortedKeysForUsersWithApp indexOfObject:title];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //return self.sortedKeys.count;
    return self.sortedKeysForUsersWithApp.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSDictionary *tDictionary = self.sortedUsersWithApp;

    //NSString *key = [self.sortedKeys objectAtIndex:section];
    NSString *key = [self.sortedKeysForUsersWithApp objectAtIndex:section];
    return ((NSArray*)[tDictionary objectForKey:key]).count;
}
Matt Hudson
  • 7,329
  • 5
  • 49
  • 66
  • This would not work for me. I would like the number of sections to vary. For example if I have no contacts starting with "B" I would not want a section "B" showing up. I have solved my question using the link in my other comment. – Tiago Veloso May 07 '12 at 08:51