以编程方式在联系人中创建组

时间:2012-07-23 12:42:56

标签: cocoa-touch abaddressbook

如何使用AddressBook框架以编程方式将新组添加到iPhone联系人?

1 个答案:

答案 0 :(得分:5)

首先查看是否存在,如果不存在,请创建它:

bool foundIt = NO;
// Protective - did we just not find it, or lose it?
CFArrayRef groups = ABAddressBookCopyArrayOfAllGroups(addrBook);
CFIndex numGroups = CFArrayGetCount(groups);
for(CFIndex idx=0; idx<numGroups; ++idx) {
    ABRecordRef groupItem = CFArrayGetValueAtIndex(groups, idx);

    CFStringRef name = (CFStringRef)ABRecordCopyValue(groupItem, kABGroupNameProperty);
//NSLog(@"Look at group named %@", name);
    bool isMatch = [newName isEqualToString:(NSString *)name];
    CFRelease(name);

    if(isMatch) {
        // NSLog(@"FOUND THE GROUP ALREADY!");
        groupNum = [NSNumber numberWithInt:ABRecordGetRecordID(groupItem)];
        [self setObject:groupNum forKey:kGroupID];
        foundIt = YES;
        break;
    }
}
CFRelease(groups);

if(!foundIt) {
    // lets create one
    ABRecordRef groupItem = ABGroupCreate();
    ABRecordSetValue(groupItem, kABGroupNameProperty, (CFStringRef *)newName, &error);
    if(!error) {
        ABAddressBookAddRecord (addrBook, groupItem, &error);   // bool ret = 
        ABAddressBookSave(addrBook, &error);

        groupNum = [NSNumber numberWithInt:ABRecordGetRecordID(groupItem)];
            //NSLog(@"FIRST groupNumber: %@", groupNum);
        [self setObject:groupNum forKey:kGroupID];
    }
    CFRelease(groupItem);
}