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,@"[email protected]",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);