从地址簿中获取所有联系人电话号码是否崩溃?

时间:2012-10-11 08:11:42

标签: 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)'

任何人都有建议为什么会崩溃?谢谢!

1 个答案:

答案 0 :(得分:2)

这不是一个问题,取决于iOS5 / iOS6,但是不同测试环境的问题。在一次案例中(我猜一个模拟器)你在地址簿中有联系人,在另一个你没有联系人。

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

因此,如果您没有任何联系并且[arrayOfPeople count]为零,那么无论如何都要进入for循环,因此当您尝试获取空的索引0处的对象时崩溃一群人。


将您的for循环中的条件替换为

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

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

当您在地址簿中没有任何联系时,当您不会下溢并且无法进入for循环时,您的崩溃就会消失。

相关问题