iOS 通訊錄–寫入信息 – iPhone手機開發技術文章 iPhone軟體開發教學課程

寫瞭基礎知識和查詢通訊錄的功能瞭現在我們來看一下寫入信息

新建修改刪除

#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);
}

發佈留言