我需要防止在我们的应用程序中显示联系人组,但是从地址簿中简单地删除组对用户来说是一种干扰。所以我试图在显示联系人之前删除它们,然后在完成后将它们添加回来,以便地址簿保持不变,iOS 联系人应用程序按原样显示组。我创建了两个数组来存储信息:
NSArray *aGroups;
NSMutableArray *aGroupMembers;
我删除组,存储它们,并在 viewWillAppear 中显示选择器:
// Remove group records for the life of this view.
CFErrorRef error;
ABAddressBookRef abRef = ABAddressBookCreate();
NSArray *groups = (NSArray *)ABAddressBookCopyArrayOfAllGroups(abRef);
if (groups.count > 0) {
// we will remove the groups so save for restoration
self.aGroups = [[NSArray alloc] initWithArray:groups];
aGroupMembers = [[NSMutableArray alloc] initWithCapacity:groups.count];
for (int i = 0; i < groups.count; i++) {
NSArray *members = (NSArray *)ABGroupCopyArrayOfAllMembers([groups objectAtIndex:i]);
NSMutableArray *memberIDs = [[NSMutableArray alloc] initWithCapacity:[members count]];
for (id member in members) {
ABRecordID ID = ABRecordGetRecordID(member);
[memberIDs addObject:[NSNumber numberWithInteger:ID]];
}
[aGroupMembers insertObject:memberIDs atIndex:i];
CFRelease(members);
[memberIDs release];
// Remove the group from the addressbook
ABAddressBookRemoveRecord(abRef, [groups objectAtIndex:i], &error);
}
CFRelease(groups);
ABAddressBookSave(abRef, nil);
self.picker.addressBook = abRef;
}
CFRelease(abRef);
然后在 viewWillDisappear 和 willResignActive 我“尝试”重新创建组,将成员重新添加到每个组并添加回地址簿。但是我无法重新添加成员,因为 ABGroupAddMember() 失败。当我在调试器中检查变量时,GroupName 和 person 的名字都是正确的。我看不到问题,并且没有设置 CFErrorRef 值。
// Restore the group records.
if (self.aGroups != nil) {
CFErrorRef error = nil;
CFTypeRef grpName = nil;
CFTypeRef firstName = nil;
ABRecordRef newGroup = nil;
ABAddressBookRef abRef = ABAddressBookCreate();
// Re-create the groups
for (int i = 0; i < self.aGroups.count; i++) {
// Create the new group
newGroup = ABGroupCreate();
grpName = ABRecordCopyValue((ABRecordRef)[self.aGroups objectAtIndex:i], kABGroupNameProperty);
ABRecordSetValue(newGroup, kABGroupNameProperty, grpName, &error);
// Create the members
NSArray *memberIDs = (NSArray*)[aGroupMembers objectAtIndex:i];
for (NSNumber *iD in memberIDs) {
ABRecordRef person = ABAddressBookGetPersonWithRecordID(abRef,iD.intValue);
firstName = ABRecordCopyValue((ABRecordRef)person, kABPersonFirstNameProperty);
BOOL bSuccess = ABGroupAddMember(newGroup, person, &error);
if (!bSuccess) {
//NSString *errorStr = [(NSString *)CFErrorCopyDescription(error) autorelease]; // this cause EXEC_BAD_ACCESS
CFRelease(error);
}
}
CFRelease(newGroup);
CFRelease(grpName);
}
// Save the changes
ABAddressBookSave(abRef, nil);
CFRelease(abRef);
self.aGroups = nil;
[aGroupMembers removeAllObjects];
aGroupMembers = nil;
}