在iOS8(iPhone 5s)中获取联系人会导致随机崩溃。 崩溃详情:http://hastebin.com/ukihinucaf.md
在线:
ABMultiValueRef multiEmails = ABRecordCopyValue(person, kABPersonEmailProperty);
这是整个功能:
-(NSArray *) getAllContacts
{
CFErrorRef *error = nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
__block BOOL accessGranted = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) {
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 {
accessGranted = YES;
}
if (accessGranted) {
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
NSMutableArray* items = [NSMutableArray arrayWithCapacity:nPeople];
for (int i = 0; i < nPeople; i++)
{
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
//get Contact email
ABMultiValueRef multiEmails = ABRecordCopyValue(person, kABPersonEmailProperty);
for (CFIndex j=0; j<ABMultiValueGetCount(multiEmails); j++) {
CFStringRef contactEmailRef = ABMultiValueCopyValueAtIndex(multiEmails, j);
NSString *contactEmail = (__bridge NSString *)contactEmailRef;
[items addObject:contactEmail];
}
}
return items;
} else {
NSLog(@"Cannot fetch Contacts :( ");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Fetch failed" message:@"Can't fetch your contacts." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
return nil;
}
}
有人知道会出现什么问题吗?
答案 0 :(得分:2)
您正在检索ABAddressBookGetPersonCount
(所有来源中所有人的计数,而不仅仅是默认来源中的人数),并且当您在迭代时使用它作为上限阈值阵列。但是数组不包含通讯录中的所有人,而只包含默认源中的所有人。因此,您可能会超出阵列中的项目数。
我建议使用CFArrayGetCount
而不是ABAddressBookGetPersonCount
。
答案 1 :(得分:2)
ABAddressBookCreateWithOptions(NULL,错误);
应该是这个
CFErrorRef error = NULL;
ABAddressBookCreateWithOptions(NULL, &error);