2

我想删除地址簿上的组。我尝试了此代码,它成功删除了组,但未删除主地址簿上的联系人。

CFErrorRef  error = NULL;

    ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();
    ABRecordRef newGroup;

    newGroup = ABAddressBookGetGroupWithRecordID(iPhoneAddressBook,groupId);
    ABAddressBookRemoveRecord(iPhoneAddressBook, newGroup, &error);
    ABAddressBookSave(iPhoneAddressBook,&error);

我的要求是每次应用程序打开时我都有一项服务可以调用,我可以从特定组中的服务获得联系。所以我删除了旧组并添加了从服务中提供的新联系人,但它将是主地址簿上的联系人的两倍,因为它只会删除组。我想删除组以及该组联系人在主地址簿上都被删除。

最后我的问题是......我如何从主地址簿中删除群组和群组联系人请帮助我......提前谢谢你..

4

1 回答 1

3

你可以这样做

-(void)RemoveContactGroup:(NSString *)name {
BOOL flag = [self CheckIfGroupExistWithName:name];

if(!flag)
{
    return;
}
CFErrorRef  error = NULL;

ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();
ABRecordRef newGroup;
//if Existing Group

newGroup = ABAddressBookGetGroupWithRecordID(iPhoneAddressBook,groupId);
NSArray *member = (__bridge NSArray *)ABGroupCopyArrayOfAllMembers(newGroup);
int nPeople = (int)[member count];

if (nPeople>0)
{
    for (int i=0; i<nPeople; i++)
    {
        ABRecordRef contactPerson = (__bridge  ABRecordRef)member[i];
        ABAddressBookRemoveRecord(iPhoneAddressBook, (ABRecordRef)contactPerson, &error);
    }
}
ABAddressBookSave(iPhoneAddressBook, NULL);
CFRelease(newGroup);
}

首先,您可以检查组是否存在,如果存在则给出组 id

-(BOOL)CheckIfGroupExistWithName:(NSString*)groupName {

hasGroup = NO;
//checks to see if the group is created ad creats group for HiBye contacts
ABAddressBookRef addressBook = ABAddressBookCreate();
CFIndex groupCount = ABAddressBookGetGroupCount(addressBook);
CFArrayRef groupLists= ABAddressBookCopyArrayOfAllGroups(addressBook);

for (int i=0; i<groupCount; i++) {
    ABRecordRef currentCheckedGroup = CFArrayGetValueAtIndex(groupLists, i);
    NSString *currentGroupName = (__bridge NSString *)ABRecordCopyCompositeName(currentCheckedGroup);

    if ([currentGroupName isEqualToString:groupName]){
        //!!! important - save groupID for later use
        groupId = ABRecordGetRecordID(currentCheckedGroup);
        hasGroup=YES;
    }
    CFRelease(currentCheckedGroup);
}

if (hasGroup==NO){
    //id the group does not exist you can create one
}
return hasGroup;
}

核实。

于 2016-02-24T04:48:09.480 回答