2013-03-25 244 views
0

我將字符串拆分爲數組中的字符,具體取決於執行操作的字符。如果文本字段爲空或其中包含1個字符,則應用程序會崩潰並顯示NSRangeException。如果有2個或更多字符,那麼它的工作原理沒有問題,部分代碼如下:索引1超出範圍

-(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; 
+0

也許嘗試更改測試來檢查數組count屬性而不是文本字段中的文本長度並回報。 – Cocoadelica 2013-03-25 15:20:40

回答

2

這行代碼中的崩潰您的應用程序,因爲如果在你的字符串中的0或1個字符,然後你的字符串,你不能在位置訪問:1

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

解決後,把你的整個代碼迴路以下if條件

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

謝謝,錯過.........看着它toooooo長:) – yeha 2013-03-25 15:34:26

+0

不客氣@yeha – 2013-03-25 15:37:46

1

你剛纔忘了刪除這一行:

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

謝謝,錯過.........看着它toooooo長:) – yeha 2013-03-25 15:34:07