4

我想获取联系人信息中保存有生日的联系人,并检索这些联系人的详细信息,如电话号码、电子邮件、生日等。

这是我尝试过的:

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);
    }

任何的想法?

4

2 回答 2

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 ;
        }

        }
    }
于 2012-05-01T08:35:31.627 回答
0

最后一个代码包含大量内存泄漏。在所有情况下,您都使用AB...Copy.. (ABRecordCopyValue, ABMultiValueCopyValueAtIndex, ABRecordCopyValue,...) 您必须释放内存!

于 2012-05-07T12:35:14.580 回答