我有一個問題。如果objectAtIndex:x爲空,我會得到一個錯誤。在我的代碼中,用戶必須插入由「/」分隔的代碼,例如32/31/43或甚至32 // 12。一切正常,但如果用戶在沒有「/」的情況下插入單個數字,我得到了圖片中顯示的錯誤,但我希望獲得一個警告視圖,告訴用戶代碼已被插入的格式不正確。我希望這很清楚。謝謝 NSArray - objectAtIndex:
1
A
回答
2
可能最好的方法是在創建它之後檢查你的數組,以確保有3個值。
NSArray *componentDepthString = [depthString componentsSeperatedByString:@"/"];
if ([componentDepthString count] == 3) {
// everything is good and you can continue with your code;
// rest of the code;
} else {
// the user input bad values or not enough values;
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:@"can't continue"
message:@"user input bad values"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}
編輯:你必須編輯標題和消息說你想要什麼,但這是就如何檢查錯誤以及如何顯示警告之前壞數據的基本理念。你將不得不添加自己的邏輯如何與用戶來處理它
2
您可以
[componentDepthString count]
在你走之前盲目地捅到陣列測試的陣列中的元件數量,確保陣列有,你就需要儘可能多的元素:
// probably a bad idea to name the array with the word "string in it
NSArray *componentDepths = [depthString componentsSeparatedByString:@"/"];
NSInteger numComponents = [componentDepths count];
if(numComponents < 3) {
// show an alert...
return;
}
// otherwise proceed as before
0
字符串「2」 componentsSeparatedByString將返回一個數組只有一個對象:字符串「2」。
您正在嘗試讀取索引爲1的對象(即第二個對象),但該數組只有一個對象。嘗試讀取超出NSArray末尾的值是錯誤的。
看來你要做的是要求輸入的值有兩個'/',所以爲什麼不先檢查一下?
if ([componentDepthString count] != 3) {
// show an alert and return
}
相關問題
- 1. NSArray valueForKey ObjectAtIndex
- 2. NSArray ObjectAtIndex:0 --- get count?
- 3. NSArray的objectAtIndex:速記
- 4. iOS NSArray objectAtIndex超出範圍
- 5. NSSet NSArray強制調用objectAtIndex?
- 6. NSArray objectAtIndex索引1超出[0,0]範圍?
- 7. 在NSArray上投射objectAtIndex的返回
- 8. 通過NSArray循環設置objectAtIndex值
- 9. UITableView ObjectAtIndex
- 10. NSRangeException與NSArray的objectAtIndex,指數超越界限
- 11. NSArray的錯誤:NSCFArray objectAtIndex索引(5)超過界限(5)
- 12. 如何檢查NSArray objectAtIndex中的值不重複?
- 13. 「{Exif}」從[NSArray objectAtIndex:]中指示的是什麼
- 14. ObjectAtIndex崩潰
- 15. objectAtIndex:0] numberOfObjects]> fetchLimit
- 16. 在NSDictionary objectAtIndex
- 17. 分配使用objectAtIndex
- 18. _PFBatchFaultingArray objectAtIndex:
- 19. UIScrollView objectAtIndex
- 20. Objective-C快速objectAtIndex:
- 21. 的NSMutableDictionary使用objectAtIndex
- 22. 關於objectAtIndex的返回值
- 23. NSArray SIGABRT
- 24. NSFetchedResultsController objectAtIndex,objectAtIndexPath,indexPathForObject不一致
- 25. NSRangeException NSArray objectAtIndex:索引11超出空數組的邊界目標C
- 26. - [__ NSCFString objectAtIndex:]的cellForRowAtIndexPath:indexPath.row
- 27. - [__ NSArrayM objectAtIndex:]問題
- 28. UIPickerView DataSource和ObjectAtIndex
- 29. 關於NSMutableArray objectAtIndex
- 30. Multidimention陣列objectAtIndex