所以我需要在 ABRecordRef 中添加一个 twitter 帐户。但是,似乎最快的方法是获取社交资料属性的多值引用,创建它的可变版本,查找它是否有 twitter 条目,如果已经有,则创建一个可变副本字典并将其替换为新字典。否则,使用 twitter 键和用户名创建一个新的字典条目。
它实际上非常冗长:
ABRecordRef person;
ABMultiValueRef oldsocials = ABRecordCopyValue(abperson, kABPersonSocialProfileProperty);
ABMutableMultiValueRef newsocials;
if(oldsocials){
newsocials = ABMultiValueCreateMutableCopy(oldsocials);
} else {
newsocials = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
}
CFIndex socialsCount = ABMultiValueGetCount(socials);
bool foundtwitter = false;
for (int k=0 ; k<socialsCount ; k++) {
CFDictionaryRef socialValue = (CFDictionaryRef)ABMultiValueCopyValueAtIndex(socials, k);
if(socialValue){
if(CFStringCompare( (CFStringRef)CFDictionaryGetValue(socialValue, kABPersonSocialProfileServiceKey), kABPersonSocialProfileServiceTwitter, 0)==kCFCompareEqualTo) {
CFMutableDictionaryRef tomutate = CFDictionaryCreateMutableCopy(socialValue);
CFDictionarySetValue(tomutate, kABPersonSocialProfileUsernameKey, toNS(thetwitter));
ABMultiValueReplaceValueAtIndex(socials, tomutate, k);
CFRelease(tomutate);
foundtwitter = true;
}
CFRelease(socialValue);
}
if(foundtwitter)
break;
}
if(!foundtwitter){
ABMultiValueAddValueAndLabel(newsocials, [NSDictionary dictionaryWithObjectsAndKeys:
(NSString *)kABPersonSocialProfileServiceTwitter, kABPersonSocialProfileServiceKey,
@"justinbieber", kABPersonSocialProfileUsernameKey,
nil], kABPersonSocialProfileServiceTwitter, NULL);
}
ABRecordSetValue(abperson, kABPersonSocialProfileProperty, newsocials, NULL);
if(oldsocials)
CFRelease(oldsocials);
CFRelease(newsocials);
光是加推特其实挺长的,感觉自己做错了什么。我的意思是,理想情况下,在另一种语言上添加类似的东西会接近这个:
person["socialServices"]["twitter"] = "@SomeUserName";
person.save();
所以我错过了什么吗?