0

I am comparing a word entered by the user to a secret word. My if statement testing whether the correct word is equal to the guessed word won't work.

@property (weak, nonatomic) IBOutlet UILabel *guesslet; //the guessed letter 
@property (weak, nonatomic) IBOutlet UILabel *Word;  //the ongoing guessed word
@property (weak, nonatomic) NSString *wrand;  //the correct word
@property (weak, nonatomic) NSString *letterguess;
- (IBAction)GuessButton;   //the button to guess the word

- (IBAction)GuessButton
{
  letterguess = guesslet.text;
  bool match = NO;
  char charInput = [guesslet.text characterAtIndex: 0];
  for(NSInteger i = 0; i < wrand.length; i++)
  {
    char tempChar = [wrand characterAtIndex: i];
    if (charInput == tempChar)
    {
      match = YES;
      NSRange InputRange = NSMakeRange(i, 1); //location, length
     Word.text = [Word.text stringByReplacingCharactersInRange: 
     InputRange withString: letterguess];
    }
    if(Word.text == randword)
    {
      UIAlertController *alert = [UIAlertController 
      alertControllerWithTitle:@”Winner!!”
      message:@”Great Job! You won!”
      preferredStyle:UIAlertControllerStyleAlert];
      UIAlertAction *okAction = [UIAlertAction
      actionWithTitle:@”Ok”
      style: UIAlertActionStyleDefault
      handler:^(UIAlertAction * action){
      }];
      UIAlertAction *cancelAction = [UIAlertAction
      actionWithTitle:@”Cancel”;
      style: UIAlertActionStyleDefault
      handler:^(UIAlertAction * action){
      }];
      [alert addAction:okAction];
      [alert addAction:cancelAction];
      [self presentViewController:alert animated: YES completion:nil];


    }
}

if(match == NO)

What am I doing wrong?

jscs
  • 63,694
  • 13
  • 151
  • 195
KYY
  • 1
  • 1
  • 2
    `=` is assignment, `==` is a test for equality, but because you are using Objective-C, you have references, so you are comparing references, not the contents of those references. You need to use `[Word.text isEqualToString:randword]`. If you are just starting out with iOS development I strongly suggest you use Swift rather than Objective-C – Paulw11 Jun 08 '17 at 20:57
  • 1
    also where is `randword` randword is coming from ? You didnt define it I think you are trying to do `[Word.text isEqualToString:wrand] ` – SpaceDust__ Jun 08 '17 at 21:00

1 Answers1

4

Using == to compare will do a pointer (or reference) comparison, if you want to compare the actual NSString's you will want to use something like

if([Word.text isEqualToString:randword]) {

}
zfetters
  • 447
  • 2
  • 11