如何从ABAddressBookRef中提取Country字段?

jow*_*wie 4 iphone country abaddressbook abmultivalue street-address

我无法理解如何访问ABAddressBookRef中的地址属性.我用电话号码做得很好:

ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSArray* phoneNumbers = (NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty);
CFRelease(phoneNumberProperty);
Run Code Online (Sandbox Code Playgroud)

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

ABMultiValueRef addressProperty = ABRecordCopyValue(person, kABPersonAddressProperty);
NSArray *address = (NSArray *)ABMultiValueCopyArrayOfAllValues(addressProperty);
Run Code Online (Sandbox Code Playgroud)

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

有人可以帮忙吗?谢谢!

小智 11

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

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

您也可以直接循环遍历,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);
Run Code Online (Sandbox Code Playgroud)