简体   繁体   中英

Get all contacts phone number from address book got crash?

I've done below code to try getting all contacts phone number from address book:

  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."];
    }
  }

However, it works well in iOS 6 but not in iOS 5. It got crash on following code:

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

The output prints:

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

Anyone has advice why it got crash? Thanks!

This is not an issue depending on iOS5/iOS6 but an issue with different testing environment. In once case (one simulator, I guess) you have contacts in your addressbook, in the other you don't.

But your test in your for loop will fail for the case when [arrayOfPeople count] is zero, because count returns an NSUInteger , which is unsigned , and subtracting -1 to 0UL creates an underflow (as -1 interpreted as an unsigned integer gives you the maximum value of an integer instead, because -1 is negative and unsigned integers can only store positive integers of course).

So when you don't have any contact and [arrayOfPeople count] is zero, you are entering into your for loop anyway thus the crash when trying to get the object at index 0 in your empty array of people.


Replace your condition in your for loop from

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

To

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

And your crash should go away as you won't underflow and won't enter in your for loop when you don't have any contact in your addressbook.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM