问题
the code bellow works great in Simulator (both iOS 4 and 5) but adds no contact on the iOS 4 device. No error is returned. Do you have any idea why?
ABAddressBookRef ab = ABAddressBookCreate();
abGroupRef = ABAddressBookGetGroupWithRecordID(ab, 1);
ABRecordRef pRef = ABAddressBookGetPersonWithRecordID(ab, 1);
ABGroupAddMember(abGroupRef, pRef, &anError);
ABAddressBookSave(ab, &anError);
Thanks, --Josef
回答1:
It's good Objective C programming practice to always check the result of a function that returns a BOOL value (such as ABGroupAddMember
or ABAddressBookSave
or the NSArray
or NSDictionary
writeToFile
methods) before checking to see if there is an error returned as one of the parameters.
Try something like this instead:
ABAddressBookRef ab = ABAddressBookCreate();
ABRecordRef abGroupRef = ABAddressBookGetGroupWithRecordID(ab, 1);
ABRecordRef pRef = ABAddressBookGetPersonWithRecordID(ab, 1);
CFErrorRef anError = NULL;
NSError * anErrorAsObjectiveCObject; // for use with toll free bridged object magic
if(ABGroupAddMember(abGroupRef, pRef, &anError))
{
if(ABAddressBookSave(ab, &anError))
{
NSLog(@"successfully saved");
} else {
anErrorAsObjectiveCObject = (__bridge_transfer NSError *) anError;
NSLog( @"error in ABAddressBookSave - %@ %@", [anErrorAsObjectiveCObject domain], [anErrorAsObjectiveCObject localizedDescription] );
}
} else {
anErrorAsObjectiveCObject = (__bridge_transfer NSError *) anError;
NSLog( @"error in ABGroupAddMember - %@ %@", [anErrorAsObjectiveCObject domain], [anErrorAsObjectiveCObject localizedDescription] );
}
回答2:
The problem was that the contacts were from google synced by exchange. There can be only local groups and local groups may only hold local contacts. This is kinda fair but the ABGroupAddMember should return an error if it is not going to add the member.
来源:https://stackoverflow.com/questions/8525360/abgroupaddmember-does-not-work-on-ios4-device