Search code examples
iphoneobjective-cnsdictionaryaddressbook

storing addressbook contacts into a nsdictionary


I'm still trying to wrap my head around using NSDictionaries, and have come into a situation where I believe I need to use one. essentially, I would like to store all the phone numbers associated with each contact into a dictionary. so far I have this:

ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *thePeople = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook); 
for (id person in thePeople)
{
    ABMultiValueRef phones =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
    NSString* name = (NSString *)ABRecordCopyCompositeName(person); 
    for (CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
    {
        NSString *phone = [(NSString *)ABMultiValueCopyValueAtIndex(phones,i) autorelease];
    }
}

I was wondering how to use a nsdictionary to store each person, and then an array of each phone value that's associated with that person.


Solution

  • What are you trying to do?

    You can put all names and phonenumbers into a plist like this:

    ABAddressBookRef addressBook = ABAddressBookCreate();
    NSArray *thePeople = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
    NSMutableArray* allPeoplesDicts = [NSMutableArray array];
    for (id person in thePeople)
    {
        ABMultiValueRef phones =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
        NSString* name = (NSString *)ABRecordCopyCompositeName(person);
        NSMutableArray* phones = [[NSMutableArray alloc] init];
        for (CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
        {
            NSString *phone = [(NSString *)ABMultiValueCopyValueAtIndex(phones,i) autorelease];
            [phones addObject:phone];
        }
        NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys:name,@"Name",phones,@"PhoneNumbers",nil];
        [phones release];
        [allPeoplesDicts addObject:personDict];
        [personDict release];
    }