ABAddressBook store values in NSDictionary

橙三吉。 提交于 2019-12-03 22:20:54

问题


I have an app that displays ABAddressBook contacts in a UITableView. Currently I'm reading the contacts into an NSDictionary, however this appears to crash for some users, which I suspect is a memory issue.

Is there another approach to display ABAddressBook contacts in a UITableView without either first storing them in an NSDictionary or using ABPeoplePicker?


回答1:


You can use following way,

ABAddressBookRef ab = ABAddressBookCreateWithOptions(NULL, NULL);
NSArray *arrTemp = (NSArray *)ABAddressBookCopyArrayOfAllPeople(ab);

The above 2 lines will create an array for all your contacts on the iPhone.

Now whatever property of a contact you want to display you can display by using the below code. For example, I want to display the first name of all contacts and then create one Mutable array called it arrContact.

NSMutableArray *arrContact = [[NSMutableArray alloc] init];
for (int i = 0; i < [arrTemp count]; i++) 
{
    NSMutableDictionary *dicContact = [[NSMutableDictionary alloc] init];
    NSString *str = (NSString *) ABRecordCopyValue([arrTemp objectAtIndex:i], kABPersonFirstNameProperty);
    @try 
    {
        [dicContact setObject:str forKey:@"name"];
    }
    @catch (NSException * e) {
        [dicContact release];
        continue;
    }
    [arrContact addObject:dicContact];
    [dicContact release];
}

Now just display it using the arrContact array in a table view..




回答2:


A different way using ARC:

ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef addressBookData = ABAddressBookCopyArrayOfAllPeople(addressBook);

CFIndex count = CFArrayGetCount(addressBookData);

NSMutableArray *contactsArray = [NSMutableArray new];

for (CFIndex idx = 0; idx < count; idx++) {
    ABRecordRef person = CFArrayGetValueAtIndex(addressBookData, idx);

    NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);

    if (firstName) {
        NSDictionary *dict = [NSDictionary dictionaryWithObject:firstName ForKey:@"name"];
        [contactsArray addObject:dict];
    }

}
CFRelease(addressBook);
CFRelease(addressBookData);



回答3:


Same as Abizern's answer, but if you want to display full names that are localized, use ABRecordCopyCompositeName. (In English names are "First Last", but in Chinese names are "LastFirst").

ABRecordRef person = CFArrayGetValueAtIndex(addressBookData, idx);
NSString *fullName = (__bridge_transfer NSString *)ABRecordCopyCompositeName(person);//important for localization


来源:https://stackoverflow.com/questions/4781211/abaddressbook-store-values-in-nsdictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!