gpt4 book ai didi

ios - 从地址簿中获取所有联系人的电话号码崩溃了吗?

转载 作者:行者123 更新时间:2023-11-28 22:47:27 25 4
gpt4 key购买 nike

我已经完成以下代码来尝试从地址簿中获取所有联系人的电话号码:

  ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *arrayOfPeople =
(__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger index = 0;
allContactsPhoneNumber = [[NSMutableArray alloc] init];

for(index = 0; index<=([arrayOfPeople count]-1); index++){

ABRecordRef currentPerson =
(__bridge ABRecordRef)[arrayOfPeople objectAtIndex:index];

NSArray *phones =
(__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(
ABRecordCopyValue(currentPerson, kABPersonPhoneProperty));

// Make sure that the selected contact has one phone at least filled in.
if ([phones count] > 0) {
// We'll use the first phone number only here.
// In a real app, it's up to you to play around with the returned values and pick the necessary value.
[allContactsPhoneNumber addObject:[phones objectAtIndex:0]];
}
else{
[allContactsPhoneNumber addObject:@"No phone number was set."];
}
}

但是,它在 iOS 6 中运行良好,但在 iOS 5 中运行不佳。它因以下代码而崩溃:

ABRecordRef currentPerson = 
(__bridge ABRecordRef)[arrayOfPeople objectAtIndex:index];

输出打印:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (0) beyond bounds (0)'

有人知道为什么会崩溃吗?谢谢!

最佳答案

这不是iOS5/iOS6的问题,而是测试环境不同的问题。在一种情况下(我猜是一个模拟器)你的地址簿中有联系人,在另一种情况下你没有。

但是当 [arrayOfPeople count] 为零时,您在 for 循环中的测试将失败,因为 count 返回一个 NSUInteger无符号-1 减去0UL 会产生下溢(如-1 解释为无符号整数,而不是给你一个整数的最大值,因为 -1 是负数,无符号整数当然只能存储正整数。

因此,当您没有任何联系人并且 [arrayOfPeople count] 为零时,您无论如何都会进入 for 循环,因此在尝试获取在你的空数组 people 中索引 0 处的对象。


for 循环中替换您的条件

for(index = 0; index<=([arrayOfPeople count]-1); index++)

for(index = 0; index<[arrayOfPeople count]; index++)

当你的地址簿中没有任何联系人时,你的崩溃应该会消失,因为你不会下溢,也不会进入你的 for 循环。

关于ios - 从地址簿中获取所有联系人的电话号码崩溃了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12835036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com