O'Reilly logo

iOS 6 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

11.7. Adding Persons to Groups

Problem

You want to assign a person entry in the address book to a group.

Solution

Use the ABGroupAddMember function.

Discussion

We learned to insert both person entries (in Recipe 11.5) and group entries (in Recipe 11.6) into the address book database. In those recipes we implemented two custom methods named newPersonWithFirstName:lastName:inAddressBook: and newGroupWithName:inAddressBook:. Now we want to add the person entry to the group we created and save the information to the address book database. Combining these three recipes, we can use the following code to achieve our goal:

- (BOOL)    addPerson:(ABRecordRef)paramPerson
              toGroup:(ABRecordRef)paramGroup
    saveToAddressBook:(ABAddressBookRef)paramAddressBook{

    BOOL result = NO;

    if (paramPerson == NULL ||
        paramGroup == NULL ||
        paramAddressBook == NULL){
        NSLog(@"Invalid parameters are given.");
        return NO;
    }

    CFErrorRef error = NULL;

    /* Now attempt to add the person entry to the group */
    result = ABGroupAddMember(paramGroup,
                              paramPerson,
                              &error);

    if (result == NO){
        NSLog(@"Could not add the person to the group.");
        return result;
    }

    /* Make sure we save any unsaved changes */
    if (ABAddressBookHasUnsavedChanges(paramAddressBook)){
        BOOL couldSaveAddressBook = NO;
        CFErrorRef couldSaveAddressBookError = NULL;
        couldSaveAddressBook = ABAddressBookSave(paramAddressBook,
                                                 &couldSaveAddressBookError);
        if (couldSaveAddressBook){
            NSLog(@"Successfully added the person to the group.");
            result = YES;
        } else {
            NSLog(@"Failed ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required