您可以使用以下方法按名称对条目进行排序:
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFMutableArrayRef peopleMutable = CFArrayCreateMutableCopy(kCFAllocatorDefault,
CFArrayGetCount(people),
people);
CFArraySortValues(peopleMutable,
CFRangeMake(0, CFArrayGetCount(peopleMutable)),
(CFComparatorFunction) ABPersonComparePeopleByName,
kABPersonSortByFirstName);
// or to sort by the address book's choosen sorting technique
//
// CFArraySortValues(peopleMutable,
// CFRangeMake(0, CFArrayGetCount(peopleMutable)),
// (CFComparatorFunction) ABPersonComparePeopleByName,
// (void*) ABPersonGetSortOrdering());
CFRelease(people);
// If you don't want to have to go through this ABRecordCopyValue logic
// in the rest of your app, rather than iterating through doing NSLog,
// build a new array as you iterate through the records.
for (CFIndex i = 0; i < CFArrayGetCount(peopleMutable); i++)
{
ABRecordRef record = CFArrayGetValueAtIndex(peopleMutable, i);
NSString *firstName = CFBridgingRelease(ABRecordCopyValue(record, kABPersonFirstNameProperty));
NSString *lastName = CFBridgingRelease(ABRecordCopyValue(record, kABPersonLastNameProperty));
NSLog(@"person = %@, %@", lastName, firstName);
}
CFRelease(peopleMutable);
或者你可以使用这种技术:
NSArray *originalArray = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
abContactArray = [originalArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
ABRecordRef record1 = (__bridge ABRecordRef)obj1; // get address book record
NSString *firstName1 = CFBridgingRelease(ABRecordCopyValue(record1, kABPersonFirstNameProperty));
NSString *lastName1 = CFBridgingRelease(ABRecordCopyValue(record1, kABPersonLastNameProperty));
ABRecordRef record2 = (__bridge ABRecordRef)obj2; // get address book record
NSString *firstName2 = CFBridgingRelease(ABRecordCopyValue(record2, kABPersonFirstNameProperty));
NSString *lastName2 = CFBridgingRelease(ABRecordCopyValue(record2, kABPersonLastNameProperty));
NSComparisonResult result = [firstName1 compare:firstName2];
if (result != NSOrderedSame)
return result;
else
return [lastName1 compare:lastName2];
}];
for (id object in abContactArray)
{
ABRecordRef record = (__bridge ABRecordRef)object; // get address book record
NSString *firstName = CFBridgingRelease(ABRecordCopyValue(record, kABPersonFirstNameProperty));
NSString *lastName = CFBridgingRelease(ABRecordCopyValue(record, kABPersonLastNameProperty));
NSLog(@"person = %@, %@", lastName, firstName);
}
前者看起来更干净,但只是另一种选择,以防万一你想避免CFRelease
在 ARC 世界中。
顺便说一下,使用ABAddressBookRequestAccessWithCompletion
在 iOS 6 中检查以确保您有权访问地址簿(通过条件检查以确保它仍然适用于早期版本的 iOS)。即使您使用的是早期版本的 iOS,您也应该手动请求用户获得许可。