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

标签 ios

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

  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/

相关文章:

ios - 使用 xcode 在 ios 应用程序上测试登录

ios - subview 的 UIStackView 不滚动

ios - 如何在选项卡式应用程序中的 ViewController 之间共享数据

ios - 如何使基于脚本退出代码的 AppCenter 构建失败?

ios - 如何区分didFinishPickingMediaWithInfo中的UIImagePickerController

ios - 在 iOS7 的 MKMapView 上显示 MKRoute

ios - 让 invokeUndefinedMethodFromWebScript 在 Swift 中工作

ios - Swift 中的子类不继承其父类(super class)的初始化程序

iOS,钥匙串(keychain) : Wrong passcode output

ios - 由于 SFSafariViewController,YSLSearchViewController 无法在 iOS 9 上工作