我有一个问题。如果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