Search code examples
objective-cxcode4if-statementarrays

How can I compare a string variable to a string in xcode?


Possible Duplicate:
String comparison in Objective-C

I realize that the question is not very specific. I am working on a simple trivia game to test a couple of things, right now it has 5 arrays, one for the questions, one for the first answer option, one for the second answer option, one for the third, and one that says which one is correct.

I have an if statement in that checks wether the button pressed matches the correct answer.

Answer2 is connected to the button that would select option b in my trivia app, strCorrect is the string array that holds the single character that says which option out of the three is right, intCurrentQuestion is just an integer I use to reference the index of the arrays.

-(IBAction)Answer2{
    if ([strCorrect objectAtIndex:intCurrentQuestion] == [NSString stringWithFormat:@"B"]){
        //do these things blah blah
    }
}

The problem is that there are no errors when it is compiled but it doesn't work either. How do I go about making this work?

For testing purpose I am cheating and passing the strCorrect to a hidden label in the nib and then comparing the label text to @"B" and it works but its...well its just awful.


Solution

  • What you're doing in your code above is comparing the memory address of two strings, not their value. Do compare two NSStrings you have to do this:

    [[strCorrect objectAtIndex:intCurrentQuestion] isEqualToString:@"B"];