0

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];
    }
}
4

2 回答 2

2

对于字符串比较,您需要使用

isEqualToString

例如:

if ([CurrentSpeedUnit isEqualToString:@"km/h"]) 
{
     // Perfrom Action
}...
于 2012-12-11T04:42:30.473 回答
0

你不应该比较这样的字符串(你比较指针而不是内容)。使用 isEqualToString。

IE

if ([CurrentSpeedUnit isEqualToString:@"km/h"]) {
...

但不是你的

if (CurrentSpeedUnit == @"km/h") {

它有时可能会起作用,但请记住避免将字符串与 == 进行比较

于 2012-12-11T04:34:24.603 回答