AddressBook.Framework应用之ABAddressBookRef,ABRecordRef,ABMutableMultiValueRef,ABMultiValueRef
AddressBook.framework是c api直接访问操作 通讯录数据库框架,AddressBookUI.framework是oc 界面交互框架;
以下代码是操作通讯录,纯c框架没有*指针定义,没有界面交互,只需导入AddressBook.framework框架。
ABAddressBookRef adbk=ABAddressBookCreate();//获取本地通讯录数据库
ABRecordRef moi=NULL;//联系人
ABRecordRef annkey=ABPersonCreate();//创建联系人
//设置联系人的值
ABRecordSetValue(annkey,kABPersonFirstNameProperty,@"annkey",NULL);
ABRecordSetValue(annkey,kABPersonLastNameProperty,@"hu",NULL);
//创建多值属性
ABMutableMultiValueRef addr=ABMultiValueCreateMutable(kABStringPropertyType);
//增加属性名和属性值,属性名为kABHomeLabel
ABMultiValueAddValueAndLabel(addr,@"annkey@qq.con",kABHomeLabel,NULL);
//设置联系人的多值邮箱属性
ABRecordSetValue(annkey,kABPersonEmailProperty, addr,NULL);
ABAddressBookAddRecord(adbk, annkey,NULL);//增加联系人
ABAddressBookSave(adbk,NULL);//保存联系人
CFRelease(addr);
CFRelease(annkey);//,即使是在arc机制里,c对象仍需手动释放
CFArrayRef sams=ABAddressBookCopyPeopleWithName(adbk, (CFStringRef)@"hu");//联系人数组,可能存在多个同名的联系人,需要通过其他属性来判断具体是哪个
for (CFIndex ix=0; ix<CFArrayGetCount(sams); ix++) {
// 从联系人数组多个sam中读取
ABRecordRef sam=CFArrayGetValueAtIndex(sams, ix);
// 获取联系人的名属性
CFStringRef last=ABRecordCopyValue(sam,kABPersonLastNameProperty);
NSLog(@" is find %@",last);
//找到符合条件的联系人
if (last&&CFStringCompare(last, (CFStringRef)@"annkey",0)==0) {
moi=sam;
}
if (last) {
//必须要判断cf对象是否为空,只有不是null才可被释放,如果不判断会报错。
CFRelease(last); //c对象需手动释放
}
}
if (NULL==moi) {
//此处通讯录肯定不为空,数据库是存在的
CFRelease(sams);
CFRelease(adbk);//c对象需手动释放
return;
}
//获取联系人的邮件属性,初始化为多值
ABMultiValueRef emails=ABRecordCopyValue(moi,kABPersonEmailProperty);
if (NULL==emails) {
NSLog(@"emails is null");
}
for (CFIndex ix=0; ix<ABMultiValueGetCount(emails); ix++) {
//联系人的属性名和属性值
CFStringRef labe1=ABMultiValueCopyLabelAtIndex(emails, ix);
CFStringRef value=ABMultiValueCopyValueAtIndex(emails, ix);
NSLog(@"i have a %@ address I%@",labe1,value);
CFRelease(labe1);
CFRelease(value);
}
NSLog(@"emails is null2");
CFRelease(emails);
CFRelease(sams);
CFRelease(adbk);