索引1超出界限

时间:2013-03-25 15:08:09

标签: objective-c xcode

我将字符串拆分为数组中的字符,具体取决于执行操作的字符。如果文本字段为空或者其中包含1个字符,则应用程序会因NSRangeException而崩溃。如果有2个或更多字符,那么它没有问题,部分代码如下:

-(IBAction) text: (id) sender{


    //labelText.text = [[NSString alloc] initWithFormat:@"%@",textField1];
    labelText.text = textField1.text;
    NSString *myString = textField1.text;

    NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
    for (int i=0; i < [myString length]; i++) {
        NSString *ichar  = [NSString stringWithFormat:@"%c", [myString characterAtIndex:i]];
        [characters addObject:ichar];
    }

    //NSLog (@"%@", [characters objectAtIndex:1]);
    //NSLog (@"%@", [characters objectAtIndex:2]);

    one1.text = (@"%@", [characters objectAtIndex:1]);

    if ([textField1.text length] == 0) {
        UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Please enter number in the box above." message:@"" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [myAlert show];
        [myAlert release];

    }


    else if ([textField1.text length] == 1){
        NSString *char1 = [characters objectAtIndex:0];
        Charr1 = char1;

    }

    else if ([textField1.text length] == 2){
        NSString *char1 = [characters objectAtIndex:0];
        NSString *char2 = [characters objectAtIndex:1];
        Charr1 = char1;
        Charr2 = char2;

    }else if ([textField1.text length] == 3){
        NSString *char1 = [characters objectAtIndex:0];
        NSString *char2 = [characters objectAtIndex:1];
        NSString *char3 = [characters objectAtIndex:2];
        Charr1 = char1;
        Charr2 = char2;
        Charr3 = char3;


    }else if ([textField1.text length] == 4){
        NSString *char1 = [characters objectAtIndex:0];
        NSString *char2 = [characters objectAtIndex:1];
        NSString *char3 = [characters objectAtIndex:2];
        NSString *char4 = [characters objectAtIndex:3];
        Charr1 = char1;
        Charr2 = char2;
        Charr3 = char3;
        Charr4 = char4;

    }else if ([textField1.text length] == 5){
        NSString *char1 = [characters objectAtIndex:0];
        NSString *char2 = [characters objectAtIndex:1];
        NSString *char3 = [characters objectAtIndex:2];
        NSString *char4 = [characters objectAtIndex:3];
        NSString *char5 = [characters objectAtIndex:4];

        Charr1 = char1;
        Charr2 = char2;
        Charr3 = char3;
        Charr4 = char4;
        Charr5 = char5;

2 个答案:

答案 0 :(得分:2)

您的代码中的这一行会导致您的应用崩溃,因为如果您的字符串中有0或1个字符,则您无法在位置访问您的字符串:1

one1.text = (@"%@", [characters objectAtIndex:1]);

解决将你的整个代码放在for循环之后的if条件

if([characters count] > 0)
{
   // your code after for loop write here 
}

答案 1 :(得分:1)

你只是忘了删除这一行:

one1.text = (@"%@", [characters objectAtIndex:1]);