如何从ABAddressBookRef中提取Country字段?

时间:2011-06-27 12:07:46

标签: iphone abaddressbook street-address country abmultivalue

我无法理解如何访问ABAddressBookRef中地址的属性。我已经用电话号码做好了:

ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSArray* phoneNumbers = (NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty);
CFRelease(phoneNumberProperty);

但是唉...我无法弄清楚如何为地址做这件事。如果我这样做:

ABMultiValueRef addressProperty = ABRecordCopyValue(person, kABPersonAddressProperty);
NSArray *address = (NSArray *)ABMultiValueCopyArrayOfAllValues(addressProperty);

我回到看起来像一个字典,但它被键入一个数组。如何访问其中的属性?我在网上看到了大量不同的建议,但它们似乎都涉及大约30行代码,只是为了从字典中提取一行!

有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:11)

对于地址,您将获得一个字典数组,以便循环遍历数组并从每个字典中提取所需的键值:

ABMultiValueRef addressProperty = ABRecordCopyValue(person, kABPersonAddressProperty);
NSArray *address = (NSArray *)ABMultiValueCopyArrayOfAllValues(addressProperty);
for (NSDictionary *addressDict in address) 
{
    NSString *country = [addressDict objectForKey:@"Country"];
}
CFRelease(addressProperty);

您也可以直接循环遍历ABMultiValueRef,而不是首先将其转换为NSArray:

ABMultiValueRef addressProperty = ABRecordCopyValue(person, kABPersonAddressProperty);

for (CFIndex i = 0; i < ABMultiValueGetCount(addressProperty); i++) 
{
    CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(addressProperty, i);
    NSString *country = (NSString *)CFDictionaryGetValue(dict, kABPersonAddressCountryKey);
    CFRelease(dict);
}

CFRelease(addressProperty);