在iPhone的地址簿中创建一个组

时间:2011-04-19 07:01:00

标签: iphone objective-c xcode

我正在使用iPhone应用程序,该应用程序使用地址簿添加联系人。我已经能够将联系人添加到地址簿中,但我遇到的问题是在我创建的组中添加联系人记录时。

联系人是在不在组中的所有联系人下创建的。以下是我使用的代码

// create address book record
ABAddressBookRef addressBook = ABAddressBookCreate(); 
// create a person  
ABRecordRef person = ABPersonCreate();  
// first name of the new person
ABRecordSetValue(person, kABPersonFirstNameProperty, @"FirstName" , nil);
// his last name 
ABRecordSetValue(person, kABPersonLastNameProperty, @"LastName", nil);  
//add the new person to the record
ABAddressBookAddRecord(addressBook, person, nil); 

ABRecordRef group = ABGroupCreate(); //create a group 
ABRecordSetValue(group, kABGroupNameProperty,@"My Group", &error); // set group's name 
ABGroupAddMember(group, person, &error); // add the person to the group         
ABAddressBookAddRecord(addressBook, group, &error); // add the group   

//save the record
ABAddressBookSave(addressBook, nil);  

// relase the ABRecordRef  variable
CFRelease(person);  

2 个答案:

答案 0 :(得分:4)

这是我的测试,我测试它,它运作良好。

ABAddressBookRef ab = ABAddressBookCreate();
CFErrorRef error;
ABRecordRef group = ABGroupCreate();
ABRecordSetValue(group, kABGroupNameProperty,@"new group", &error);
ABAddressBookAddRecord(ab, group, &error);
ABAddressBookSave(ab, &error);
//Create new person and save to this group
ABRecordRef record = ABPersonCreate();
BOOL isSuccess ;

isSuccess  = ABRecordSetValue(record, kABPersonNicknameProperty,@"GroupMember nick name", &error);
isSuccess = ABRecordSetValue(record, kABPersonMiddleNameProperty, @"Middle name", &error);

ABMutableMultiValueRef copyOfPhones = ABMultiValueCreateMutable(kABPersonPhoneProperty);

CFTypeRef phone= CFSTR("123000222111");

ABMultiValueAddValueAndLabel(copyOfPhones, phone,kABPersonPhoneMobileLabel,NULL);

isSuccess = ABRecordSetValue(record, kABPersonPhoneProperty, copyOfPhones, &error);

isSuccess = ABAddressBookAddRecord(ab, record, &error);
isSuccess = ABAddressBookSave(ab, &error);

ABGroupAddMember(group, record, &error);

NSLog(@"is success %d", isSuccess);

ABAddressBookSave(ab, &error);
CFRelease(group);  

答案 1 :(得分:0)

首先需要将Person保存到地址簿,然后再将其添加到组中,这意味着您必须添加

ABAddressBookSave(addressBook, nil);

在将此人添加到群组之前,在您的情况下,它将在创建群组之前。