Reputation: 149
I am splitting a string into characters in an array, depending on the character an action is performed. If the textfield is blank or has 1 character in it the app crashed with a NSRangeException. If there are 2 or more characters then it works with no issues, partial code as follows:
-(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;
Upvotes: 0
Views: 103
Reputation: 13600
this line in your code crashes your app because if there is a 0 or 1 character in your string then your string you cannot access at location:1
one1.text = (@"%@", [characters objectAtIndex:1]);
to resolve put your whole code after for loop in following if condition
if([characters count] > 0)
{
// your code after for loop write here
}
Upvotes: 2
Reputation: 9718
You just forgot to remove this line:
one1.text = (@"%@", [characters objectAtIndex:1]);
Upvotes: 1