iphonesortingnsmutablearraynsarrayabrecord

Sorting ABRecords alphabetically on iPhone


I'm retrieving contact names with this code:

for( int i = 0 ; i < n ; i++ )
{
    Contact *c = [[Contact alloc] init];

    ABRecordRef ref = CFArrayGetValueAtIndex(all, i);
    NSString *firstName = (NSString *)ABRecordCopyValue(ref, kABPersonFirstNameProperty);
    NSString *lastName = (NSString *)ABRecordCopyValue(ref, kABPersonLastNameProperty);
    c.firstName = firstName; //[NSString stringWithFormat:@"%@ %@", firstName, lastName];
    c.lastName = lastName;

    [contacts addObject:c];

    [c release];
}

Does anyone know a way of ordering this list alphabetically? I've read about sortedArrayUsingSelector:@selector(compare:) but I have no idea how that is supposed to work.


Solution

  • NSSortDescriptor *mySorter = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES];
    [contacts sortUsingDescriptors:[NSArray arrayWithObject:mySorter]];
    [mySorter release];