Is there a way to get a reference to the address book in the user's iPhone, filter out all contacts that don't begin with letter 'A', and then display that filtered address book? This sounds possible with a UITableView, but i开发者_如何学JAVAs there a special view that comes with all address book functionality?
To get an array of all people whose lastname starts with A, you would use something like:
ABAddressBook *ab = [ABAddressBook sharedAddressBook];
ABSearchElement *startsWithA =[ABPerson searchElementForProperty:kABLastNameProperty
label:nil key:nil
value:@"A"
comparison:kABPrefixMatchCaseInsensitive];
NSArray *peopleFound =
[ab recordsMatchingSearchElement:startsWithA];
Once you get an array, you can use it in any custom view you need.
This code fragment assumes that filteredPeople is the dataSource of the table view you want to populate with all address book contacts who have names starting with A.
This answer should help you as well : Blank field showing up on iPhone AddressBook, how to debug?
Also apple has extensive details on "Direct Interaction: Programmatically Accessing the Database" at http://developer.apple.com/library/ios/#documentation/ContactData/Conceptual/AddressBookProgrammingGuideforiPhone/Chapters/DirectInteraction.html%23//apple_ref/doc/uid/TP40007744-CH6-SW1
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFMutableArrayRef peopleMutable = CFArrayCreateMutableCopy(
kCFAllocatorDefault,
CFArrayGetCount(people),
people
);
NSMutableArray *allNames = (NSMutableArray*)peopleMutable;
filteredPeople = [[NSMutableArray alloc] init ];
for (id person in allNames) {
NSMutableString *firstName = [(NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty) autorelease];
if ([firstName length] > 0){
NSString* firstChar = [firstName substringToIndex:1];
if ([firstChar isEqualToString:@"A"] || [firstChar isEqualToString:@"a"]){
[filteredPeople addObject:person];
}
}
}
[self.theTableView reloadData];
CFRelease(addressBook);
CFRelease(people);
CFRelease(peopleMutable);
精彩评论