【问题标题】:Programmatically create a group in contacts以编程方式在联系人中创建组
【发布时间】:2012-07-23 12:42:55
【问题描述】:

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

【问题讨论】:

  • 堆栈溢出是针对特定的编程问题,而不是有人会为您编写程序的地方。
  • 这有点苛刻不是吗?它的几行代码不是程序。
  • 感谢大卫,你的代码工作得很好,我是 ios 编程的新手,这就是我问这类问题的原因。
  • 你好,玛丽,你能给我你的代码吗,我需要我的应用程序。

标签: cocoa-touch abaddressbook


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-01
    • 2011-09-02
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 2015-03-15
    相关资源
    最近更新 更多