Reputation: 1394
I am trying to get contacts list like this:
CFErrorRef *error = nil;
ABAddressBookRef addressBook = nil;
__block BOOL accessGranted = NO;
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined ||
ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
addressBook = ABAddressBookCreateWithOptions(NULL, error);
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
accessGranted = granted;
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusDenied ||
ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusRestricted) {
return nil;
}
if (!accessGranted) {
if (addressBook) CFRelease(addressBook);
return nil;
}
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
if (nPeople <= 0) {
CFRelease(addressBook);
return nil;
}
ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName);
if (!allPeople) return nil;
NSMutableArray *contactsArray = [NSMutableArray arrayWithCapacity:nPeople];
for (CFIndex i = 0; i < nPeople; ++i) {
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
if (!person) continue;
ContactData *contact = [ContactData new];
contact.firstName = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
It is working on my iPhone 5s and simulator, but the build is crashing on the tester iPod device on the line with SIGSEGV:
contact.firstName = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
Here is the stack:
3 AppSupport 0x34129a04 CPRecordCopyProperty 4 AppSupport 0x34129a04 CPRecordCopyProperty 5 AddressBook 0x2fd6ad22 ABRecordCopyValueUnfiltered 6 AddressBook 0x2fd6abc6 ABRecordCopyValue
Upvotes: 3
Views: 449
Reputation: 86
I had the same error, the problem is that:
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName);
and
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
are giving a different number of contacts (so in your case nPeople
is probably bigger than allPeople
, which causes the crash). "source" doesn't seem to be giving all the contacts in the address book. Changing it to nil
solved it for me. Also, to be sure I would do: nPeople = CFArrayGetCount(allPeople);
The solution is very well explained by Jokinryou Tsui in this post: ABAddressBookCopyArrayOfAllPeople and ABAddressBookGetPersonCount return different sizes
(This is my first post, so I'm not sure if I broke any rules or followed the right procedure. I hope the answer helps!)
Upvotes: 4