首页 > 代码库 > iOS 通讯录--写入信息

iOS 通讯录--写入信息

写了基础知识和查询通讯录的功能了现在我们来看一下写入信息

  • 新建
  • 修改
  • 删除
#pragma mark  - 写入联系人信息

//创建联系人
- (void) creatNewRecord
{
    CFErrorRef error = NULL;
    
    //创建一个通讯录操作对象
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    
    //创建一条新的联系人纪录
    ABRecordRef newRecord = ABPersonCreate();
    
    //为新联系人记录添加属性值
    ABRecordSetValue(newRecord, kABPersonFirstNameProperty, (__bridge CFTypeRef)@"雪松", &error);
    
    //创建一个多值属性
    ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    ABMultiValueAddValueAndLabel(multi, (__bridge CFTypeRef)@"12345678990", kABPersonPhoneMobileLabel, NULL);
    ABMultiValueAddValueAndLabel(multi, (__bridge CFTypeRef)@"11234567890", kABPersonPhoneIPhoneLabel, NULL);
    
    //将多值属性添加到记录
    ABRecordSetValue(newRecord, kABPersonPhoneProperty, multi, &error);
    CFRelease(multi);
    
    //添加记录到通讯录操作对象
    ABAddressBookAddRecord(addressBook, newRecord, &error);
    
    //保存通讯录操作对象
    ABAddressBookSave(addressBook, &error);
    CFRelease(newRecord);
    CFRelease(addressBook);
}

- (void) editRecord
{
    CFErrorRef error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    ABRecordID recordID = [personIDASNumber intValue];
    ABRecordRef record = ABAddressBookGetPersonWithRecordID(addressBook, recordID);
    
    //设置电话号码
    ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    ABMultiValueAddValueAndLabel(multi, (__bridge CFTypeRef)@"12345678900", kABPersonPhoneMobileLabel, NULL);
    ABMultiValueAddValueAndLabel(multi, (__bridge CFTypeRef)@"12345678900", kABPersonPhoneIPhoneLabel, NULL);
    
    //添加电话号码到数据库
    ABRecordSetValue(record, kABPersonPhoneProperty, multi, &error);
    CFRelease(multi);
    
    //保存到数据库
    ABAddressBookSave(addressBook, &error);
    CFRelease(addressBook);
    
}

- (void)deleteRecord
{
    CFErrorRef error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    ABRecordID recordID = [personIDASNumber intValue];
    ABRecordRef record = ABAddressBookGetPersonWithRecordID(addressBook, recordID);
    
    //删除记录
    ABAddressBookRemoveRecord(addressBook, record, &error);
    
    //保存到数据库
    ABAddressBookSave(addressBook, &error);
    CFRelease(addressBook);
}


iOS 通讯录--写入信息