2011-05-29 99 views
1

我有一个问题。如果objectAtIndex:x为空,我会得到一个错误。在我的代码中,用户必须插入由“/”分隔的代码,例如32/31/43或甚至32 // 12。一切正常,但如果用户在没有“/”的情况下插入单个数字,我得到了图片中显示的错误,但我希望获得一个警告视图,告诉用户代码已被插入的格式不正确。我希望这很清楚。谢谢 enter image description hereNSArray - objectAtIndex:

回答

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 
}