我正在使用此简单代码在ios 7中获取通讯簿的所有联系人。我的地址中有155个联系人。当我以别人的名字登录时,我从地址簿中获得了34个正确的名字(显然是随机地),其中15个名字为null,然后在第50条上,一次错误的访问崩溃
NSString *firstNames = (__bridge NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty)
我尝试过登录名,或图像未更改。我试图避免对空对象进行ABRecordCopyValue更改。我尝试对> 50的项目执行ABRecordCopyValue,对50到150的项目也得到了相同的结果。我在做什么错?除了正确的值和null之外,还能返回什么ABRecordCopyValue?
+(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
数组中的条目数,就像您认为的那样。当nPeople
已经提供了简单明了的方法时,您使用了一种奇怪的方法来获取CFArray
。
我认为这可以工作:
CFIndex nPeople = CFArrayGetCount(allPeople);
另外,在使用
person
之前,还需要检查它是否不是NULL
:ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
NSAssert(person, @"Non-person detected!");
关于ios - 可以返回什么ABRecordCopyValue? (解决访问错误),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24651715/