I’m new to xcode and am stuck on this one action.
I’m trying to add a “Negative” sign or “-” to a field when a button is clicked.
The following code works when someone enters a number into the field… it will add or remove a negative sign to it.
However, if the field is blank and you click on the button it throws an error.
Here’s the code:
- (IBAction)fPosNeg:(id)sender {
NSMutableString *str = [userFahrenheit.text mutableCopy];
char iChar = [str characterAtIndex:0];
if (iChar == '-') {
userFahrenheit.text = [userFahrenheit.text substringFromIndex:1];
} else if (iChar != '-') {
[str insertString:@"-" atIndex:0];
userFahrenheit.text = str;
} else {
userFahrenheit.text = [NSString stringWithFormat:@"-"];
}
}
Here’s the error:
Terminating app due to uncaught exception ‘NSRangeException’, reason:
‘-[__NSCFString characterAtIndex:]: Range or index out of bounds’
You need to put a check before calling this -> [str characterAtIndex:0];
check will be