views:

13

answers:

1

I'm trying to write a basic DST converter. I have a segmented control with 3 choices, their titles (surprisingly) are Distance, Speed and Time. I have 2 input text fields and a calculate button, as well as 2 labels for each text field with the type of measurement required and it's units. Making a selection on the segmented control should update the view accordingly. The variables have all been declared as IBOutlets, @property, @synthesize, and the code sits in an IBAction method, which is connected to the segmented control. The following code does not work, am I missing something completely obvious? (NSLog shows the correct title)

NSString *choice;    
choice = [dstChoiceSegmentedControl titleForSegmentAtIndex: dstChoiceSegmentedControl.selectedSegmentIndex];
    NSLog(@"Choice |%@|", choice);
    if (choice == @"Distance") {
        firstLabel.text = @"Speed:";
        firstUnitsLabel.text = @"kts";
        secondLabel.text = @"Time:";
        secondUnitsLabel.text = @"hrs";
        answerUnitsLabel.text = @"nm";
    } else if (choice == @"Speed") {
        firstLabel.text = @"Distance:";
        firstUnitsLabel.text = @"nm";
        secondLabel.text = @"Time:";
        secondUnitsLabel.text = @"hrs";
        answerUnitsLabel.text = @"kts";
    } else if (choice == @"Time") {
        firstLabel.text = @"Distance:";
        firstUnitsLabel.text = @"nm";
        secondLabel.text = @"Speed:";
        secondUnitsLabel.text = @"kts";
        answerUnitsLabel.text = @"hrs";
    }

Thanks for your help (and I hope it's not some silly error that is staring me right in the face)!

A: 

You cannot compare strings this way. You need to do:

[choice isEqualToString:@"Distance"];

But if I were you, I'd check for the indicies instead.

edit: To explain it further: what you're doing with choice == @"Distance" is comparing a pointer with a string, which will not work. You need to call the string objects comparing method as shown above.

Toastor
Well, the string itself is also a pointer.
Jacob Relkin
Thanks, that worked a treat. As I'm relatively new to programming, why is it better to check for the indicies (which I'm now doing) rather than whether the strings match?
churchill614
It takes up less ressources to compare integers then it takes to compare strings and thus may be a little bit faster. You propably wouldn't feel the difference, though.
Toastor
Thanks for your help. And that's 2 new things I've learnt so far today!
churchill614