Getting iPhone contacts sorted by date created

11 Nov 2011

Let’s say you add a contact to your iPhone, and the next day you wake up, and you can’t remember that contact’s name. How do you find the number?

Using iPhone’s Address Book API, you can do that quite easily. The following snippet uses the AddressBook framework.

contacts = [NSMutableArray array];
ABAddressBookRef addressBook = ABAddressBookCreate( );
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople( addressBook );
CFIndex nPeople = ABAddressBookGetPersonCount( addressBook );

for ( int i = 0; i < nPeople; i++ )
{
    ABRecordRef ref = CFArrayGetValueAtIndex( allPeople, i );
    if ( ABRecordGetRecordType(ref) == kABPersonType) {
        Contact *c = [[Contact alloc] init];
        c.name = (__bridge NSString*)ABRecordCopyCompositeName (ref);
        c.createdAt = (__bridge NSDate*)ABRecordCopyValue( ref, kABPersonCreationDateProperty );
        [contacts addObject:c];
    }
}

[contacts sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [[obj2 createdAt] compare:[obj1 createdAt]];
}];

NSLog(@"Contacts %@", contacts);