我需要防止在我們的應用程序中顯示聯繫人組,但是它侵入用戶從地址簿中刪除組。因此,我試圖在顯示聯繫人之前將其刪除,然後在完成後將其添加回來,以便AddressBook保持不變,iOS Contacts應用程序按原樣顯示這些組。我創建了兩個陣列存儲的信息:爲什麼ABGroupAddMember失敗?它返回NO並且不設置CFErrorRef值
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;
}
http://stackoverflow.com/questions/15470733/unable-to-add-contacts-into-specific-group-in-iphone-using-abgroupaddmember/23862110#23862110 – Yong
http://stackoverflow.com/a/31998913/2359049 –