2012-10-11 28 views
0

我下面的代碼做了嘗試獲得從地址簿中的所有聯繫人的電話號碼:獲取通訊錄中的所有聯繫人電話號碼都崩潰了嗎?

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)' 

任何人有意見,爲什麼它得到了崩潰?謝謝!

回答

2

這不是取決於iOS5/iOS6的問題,而是不同測試環境的問題。在一次的情況下(我猜測一個模擬器),你的地址簿中有聯繫人,而另一個則沒有。

但在你for循環測試將失敗的情況下[arrayOfPeople count]是零,因爲count返回NSUInteger,這是無符號,並減去-10UL創建溢(如-1解釋爲無符號整數給出你是一個整數的最大值,因爲-1是負數,而無符號整數當然只能存儲正整數)。

因此,如果您沒有任何聯繫並且[arrayOfPeople count]爲零,那麼無論如何您都會進入for循環,因此嘗試在空陣列中的索引0處獲取對象時發生崩潰。


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

更換你的病情在for環路

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

而且你應該崩潰消失,你不會溢出,也不會在你的for進入當你的地址簿中沒有任何聯繫時循環。

+0

非常感謝,你救了我的命:')這是一個非常微不足道的問題 – Rendy

相關問題