我將字符串拆分爲數組中的字符,具體取決於執行操作的字符。如果文本字段爲空或其中包含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;
也許嘗試更改測試來檢查數組count屬性而不是文本字段中的文本長度並回報。 – Cocoadelica 2013-03-25 15:20:40