我有个问题。如果objectAtIndex:x为空,我会得到一个错误。在我的代码中,用户必须插入一个由"/“分隔的代码,例如32/31/43甚至32//12。一切正常,但是如果用户插入一个没有"/”的单个数字,我会得到图片中显示的错误,但我希望得到一个警告视图,告诉用户代码插入的格式错误。我希望这是清楚的。谢谢

发布于 2011-05-30 03:06:13
也许最好的方法是在创建数组后检查它,以确保有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];
}编辑:您必须编辑标题和消息,以表明您想要什么,但这是关于如何在错误发生前检查错误数据以及如何显示警告的基本思想。你将不得不添加你自己的逻辑如何处理它与用户
发布于 2011-05-30 03:08:15
您可以使用以下命令测试数组中的组件数量
[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发布于 2011-05-30 03:12:34
对于字符串"2“,componentsSeparatedByString将返回一个只有一个对象的数组:字符串"2”。
您正在尝试读取索引为1的对象(即第二个对象),但该数组只有一个对象。尝试从NSArray末尾以外的位置读取值是错误的。
看起来你想要做的是要求输入的值有两个‘/’,所以为什么不先检查一下呢?
if ([componentDepthString count] != 3) {
// show an alert and return
}https://stackoverflow.com/questions/6169760
复制相似问题