问题描述
我正在使用这个简单的代码来获取ios 7中地址簿的所有联系人。我的地址中有155个联系人。当我记录人们的姓名时,我从我的地址簿中获取了34个正确的名字(显然是随机的),15个名称为null,然后在第50个项目上有一个糟糕的访问崩溃
I'm using this simple code to get all contacts of the address book in ios 7. I have 155 contacts in my address. When i log people firstNames i obtain 34 correct names picked (apparently randomly) from my address book, 15 names null and then on item 50 a bad access crash on line
NSString *firstNames = (__bridge NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty)
我尝试了loggin surname,或者图片没有变化。我试图避免在null对象上进行ABRecordCopyValue而不进行任何更改。我尝试在项目> 50上执行ABRecordCopyValue,并在50到150的项目上得到相同的结果。我做错了什么?什么ABRecordCopyValue可以返回正确的值并且为空?
I tried loggin surname, or image getting no changes. I tried to avoid doing ABRecordCopyValue on null object getting no changes. I tried to execute ABRecordCopyValue on item >50 and got the same result on items from 50 to 150. What i'm doing wrong? What ABRecordCopyValue can return beside correct values and null?
+(NSArray *)getAllContactsAddress
{
CFErrorRef *error = nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
// SUPPOSE access has been granted
BOOL accessGranted = true;
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++)
{
ContactsData *contacts = [ContactsData new];
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
NSString *firstNames = (__bridge NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSLog(@"%@",firstNames);
}
}
推荐答案
我想 问题是 nPeople
是错误的值并且不匹配 allPeople
数组中的条目数,就像你想象的那样。当 CFArray
已经提供了直接的方法时,你使用了一种奇怪的方法来获取 nPeople
。
I think the issue is that nPeople
is the wrong value and doesn't match the number of entries in the allPeople
array, like you assume it does. You have used a strange method of getting nPeople
when CFArray
already provides a straight-forward method.
我认为这样可行:
CFIndex nPeople = CFArrayGetCount(allPeople);
此外,您需要检查 person
是否为非 - NULL
使用前:
Also you need to check if person
is non-NULL
before using it:
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
NSAssert(person, @"Non-person detected!");
这篇关于ABRecordCopyValue可以返回什么? (解决不良访问)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!