ABRecordCopyValue可以返回什么? (解决不良访问)

时间:2014-07-09 10:51:30

标签: ios addressbook abrecord

我正在使用这个简单的代码来获取ios 7中地址簿的所有联系人。我的地址中有155个联系人。当我记录第一个人名字时,我从我的地址簿中获取了34个正确的名字(显然是随机的),15个名称为null,然后在第50个项目上就是一个糟糕的访问崩溃

   NSString *firstNames = (__bridge NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty)

我尝试过登录姓氏,或者图片没有变化。我试图避免对null对象进行ABRecordCopyValue而不进行任何更改。我尝试在项目> 50上执行ABRecordCopyValue,并在50到150的项目上得到相同的结果。我做错了什么? ABRecordCopyValue可以在正确的值旁边返回什么并且为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);
    }
}

1 个答案:

答案 0 :(得分:5)

认为 (我实际上非常确定)问题是nPeople是错误的值并且与之不匹配allPeople数组中的条目数,就像您假设的那样。当nPeople已经提供了直接的方法时,您使用了一种奇怪的方法来获取CFArray

我认为这样可行:

CFIndex nPeople = CFArrayGetCount(allPeople);

在使用之前,您还需要检查person是否为非NULL

ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
NSAssert(person, @"Non-person detected!");