我正在尝试获取这样的联系人列表:
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);
它正在我的iPhone 5s和模拟器上工作,但是在使用SIGSEGV的线路上,测试版iPod设备上的版本崩溃了:
contact.firstName = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
这是堆栈:
3 AppSupport 0x34129a04 CPRecordCopyProperty 4 AppSupport 0x34129a04 CPRecordCopyProperty 5 AddressBook 0x2fd6ad22 ABRecordCopyValueUnfiltered 6地址簿0x2fd6abc6 ABRecordCopyValue
答案 0 :(得分:4)
我遇到了同样的错误,问题是:
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName);
和
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
正在提供不同数量的联系人(因此在您的情况下nPeople
可能大于allPeople
,这会导致崩溃)。 “来源”似乎没有给出地址簿中的所有联系人。将其更改为nil
为我解决了这个问题。另外,我确定会这样做:nPeople = CFArrayGetCount(allPeople);
Jokinryou Tsui在这篇文章中解释了解决方案:ABAddressBookCopyArrayOfAllPeople and ABAddressBookGetPersonCount return different sizes
(这是我的第一篇文章,所以我不确定我是否违反任何规则或遵循正确的程序。我希望答案有所帮助!)