Reputation: 39
it is probably a very simple problem but I spent already a lot of time on it and just have given up... I have a button and a textfield for speed calculations. I want the button label change once the button is pressed (km/h >> mph >> m/s >> km/h and so on) and speed recalculated. It sometimes works fine but very often it jumps to "else" statement even if the CurrentSpeedValue is @"km/h". Could anyone help? Maybe it would be better to use switch-case method but how should it be stated?
- (IBAction)speedChange:(id)sender {
//CurrentSpeedUnit is saved to NSUserDefault in another action
if (CurrentSpeedUnit == @"km/h") {
[sender setTitle:@"mph" forState:UIControlStateNormal];
CurrentSpeedUnit = @"mph";
float speedToPrint = ([textSpeed.text floatValue]) / 1.609344;
textSpeed.text = [[NSString alloc] initWithFormat:@"%.3f", speedToPrint];
} else if (CurrentSpeedUnit == @"mph") {
[sender setTitle:@"m/s" forState:UIControlStateNormal];
CurrentSpeedUnit = @"m/s";
float speedToPrint = ([textSpeed.text floatValue]) * 1.609344 / 3.6;
textSpeed.text = [[NSString alloc] initWithFormat:@"%.3f", speedToPrint];
} else {
[sender setTitle:@"km/h" forState:UIControlStateNormal];
CurrentSpeedUnit = @"km/h";
float speedToPrint = ([textSpeed.text floatValue]) * 3.6;
textSpeed.text = [[NSString alloc] initWithFormat:@"%.3f", speedToPrint];
}
}
Upvotes: 0
Views: 152
Reputation: 6218
For string comparison you need to use
isEqualToString
For Example:
if ([CurrentSpeedUnit isEqualToString:@"km/h"])
{
// Perfrom Action
}...
Upvotes: 2
Reputation: 6032
You should not compare strings like that (you compare pointers but not the contents). Use isEqualToString.
i.e.
if ([CurrentSpeedUnit isEqualToString:@"km/h"]) {
...
but not your
if (CurrentSpeedUnit == @"km/h") {
It may work sometimes, but just remember to avoid comparing strings with ==
Upvotes: 0