我想获取联系人信息中保存了生日的联系人 检索这些联系人的详细信息,如电话号码,电子邮件,生日等。
以下是我的尝试:
ABAddressBookRef myAddressBook = ABAddressBookCreate();
NSArray *allPeople = (NSArray *)ABAddressBookCopyArrayOfAllPeople(myAddressBook);
contactList = [[NSMutableArray alloc]init];
for (id record in allPeople)
{
NSMutableDictionary *newRecord = [[NSMutableDictionary alloc] init];
CFTypeRef bDayProperty = ABRecordCopyValue((ABRecordRef)record, kABPersonBirthdayProperty);
if (ABRecordCopyValue((ABRecordRef)record, kABPersonBirthdayProperty))
{
NSDate *date=(NSDate*)bDayProperty;
[newRecord setObject:date forKey:@"birthDate"];
date=nil;
[date release];
}
CFRelease(myAddressBook);
}
任何想法?
答案 0 :(得分:3)
你可以尝试这段代码。
ABAddressBookRef m_addressbook = ABAddressBookCreate();
if (!m_addressbook) {
NSLog(@"opening address book");
}
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(m_addressbook);
CFIndex nPeople = ABAddressBookGetPersonCount(m_addressbook);
NSLog(@" cfindex %ld",nPeople);
for ( int i=0;i < nPeople;i++) {
NSMutableDictionary *dOfPerson=[NSMutableDictionary dictionary];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
//For username and surname
CFStringRef firstName, lastName;
firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
[dOfPerson setObject:[NSString stringWithFormat:@"%@ %@", firstName, lastName] forKey:@"name"];
//For Email ids
ABMutableMultiValueRef eMail = ABRecordCopyValue(ref, kABPersonEmailProperty);
if(ABMultiValueGetCount(eMail) > 0) {
[dOfPerson setObject:(NSString *)ABMultiValueCopyValueAtIndex(eMail, 0) forKey:@"email"];
[contactList addObject:dOfPerson];
}
//For Phone number
NSString* mobileLabel;
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++)
{
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, j);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
[dOfPerson setObject:(NSString*)ABMultiValueCopyValueAtIndex(phones, i) forKey:@"Phone"];
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
[dOfPerson setObject:(NSString*)ABMultiValueCopyValueAtIndex(phones, i) forKey:@"Phone"];
break ;
}
}
}
答案 1 :(得分:0)
最后一个代码包含大量内存泄漏。在所有情况下,你都要使用 AB ...复制.. (ABRecordCopyValue,ABMultiValueCopyValueAtIndex,ABRecordCopyValue,...)你必须释放内存!