如何找出一个人的父母群体?

时间:2012-11-17 02:45:46

标签: ios addressbook

在MAC平台上,ABPerson类有一个parentGroups属性,该属性告诉我们该人所属的组。但是在IOS平台上,没有这样的方法或属性..

如何找出一个人的父母群体?我是否需要逐个搜索所有群组?

感谢。

3 个答案:

答案 0 :(得分:6)

另一个线程提到了ABPersonCopyParentGroups - 但这是错误 -n.a.在ios上。

没有api调用所以需要直接执行此操作

ABRecordRef personToFind = ....
ABRecordID id = ABRecordGetRecordID(personToFind);

NSArray *groups = (__bridge_transfer NSArray*)ABAddressBookCopyArrayOfAllGroups(bookRef);
for(ABGroupRef group in groups) {
    NSArray *members = (__bridge_transfer NSArray*)ABGroupCopyAllMembers(group);
    for(ABRecordRef member in members) {
        if(id == ABRecordGetRecordID(member){
            NSLog(@"found in group %@!", ABGroupCopyProperty(group, kABGroupName);
            break;
        }
    }            
}

*键入内联,无保证 - 可能存在拼写错误!

答案 1 :(得分:1)

我很难使用Daij-Djan的答案,所以我重写了它:

CFArrayRef groupsRef = ABAddressBookCopyArrayOfAllGroups(myAddressBook);
if(groupsRef) {
    NSUInteger groupsCount = CFArrayGetCount(groupsRef);

    for(NSUInteger idx = 0; idx < groupsCount; ++idx) {
        ABRecordRef groupRef = CFArrayGetValueAtIndex(groupsRef, idx);
        ABRecordID groupID = ABRecordGetRecordID(groupRef);
        CFArrayRef membersRef = ABGroupCopyArrayOfAllMembers(groupRef);
        if(membersRef) {
            NSUInteger membersCount = CFArrayGetCount(membersRef);

            for(NSUInteger idx = 0; idx < membersCount; ++idx) {
                ABRecordRef memberRef = CFArrayGetValueAtIndex(membersRef, idx);
                ABRecordID memberID = ABRecordGetRecordID(memberRef);

                // your code
            }
            CFRelease(membersRef);
        }
    }
    CFRelease(groupsRef);
}

答案 2 :(得分:1)

我扫描其中的所有组和人员,并将人员记录ID和组记录ID保存到NSDictionary。 我保留这个NDDictionary直到应用程序消失,所以只需要查找此NSDictionary的人员组ID。

NSMutableDictionary *dic = [NSMutableDictionary dictionary];
CFArrayRef allGroup = ABAddressBookCopyArrayOfAllGroups( AddressBookManager.addressBook );

CFIndex nGroup = ABAddressBookGetGroupCount(AddressBookManager.addressBook);

NSMutableArray *array = [[NSMutableArray alloc] init];
for (CFIndex index = 0; index < nGroup; index ++) 
{
    ABRecordRef group = CFArrayGetValueAtIndex(allGroup, index);
    ABRecordID groupID = ABRecordGetRecordID(group);

    CFArrayRef allPeople = ABGroupCopyArrayOfAllMembers(group);

    CFIndex nPeople = CFArrayGetCount(allPeople);
    for( CFIndex personIndex = 0; personIndex < nPeople; personIndex++ )
    {
        ABRecordRef person = CFArrayGetValueAtIndex( allPeople, personIndex );
        ABRecordID personID = ABRecordGetRecordID(person);

        NSNumber *value = [NSNumber numberWithInt:groupID];
        NSString *key = [NSString stringWithFormat:@"%d", personID];
        [dic setValue:value forKey:key];
    }
    CFRelease(allPeople);
}