Blank textField (Calculation) crashes app.
I have an app that does a simple calculation from 2 text fields, the result is then displayed as label text. This is fine as long at each text field is populated, if no data is entered and the calculate button is pressed then the app closed. I assumed that blank would return a value of 0 and result would be displayed as 0. My code is as follows:
-(IBAction) tonerCalc: (id) sender{
NSString *tString;
int myInt = [textField1.text intValue];
int myInt1 = [textField2.text intValue];
int total = myInt/(myInt1/5);
开发者_JAVA技巧 tString = [[NSString alloc] initWithFormat:@"%i",total];
labelText.text = tString;
[tString release];
} How can I stop the crash, I think it has something to do with the calculation. Any help is greatly appreciated.
intValue will return 0 because there is no number in the string. But then you're doing a division by zero.
You can put a check like
`if(![textField1.text isEqualToString:@""]|| ![textField2.text isEqualToString:@""])`
{
//perform calculation
}
else
{
//show alert that text field are empty
}
and if the condition is true then you can make your calculation do otherwise show alert.It will stop the crash.
精彩评论