アプリ内で連絡先グループが表示されないようにする必要がありますが、アドレスブックからグループを削除するだけではユーザーの邪魔になります。そのため、連絡先を表示する前にそれらを削除し、終了したら追加して、AddressBook を変更せずに iOS 連絡先アプリにグループをそのまま表示しようとしています。情報を格納するための 2 つの配列を作成しました。
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;
}