Search code examples
objective-cuitextfieldalertview

How can I make it so only 1 "if-statement" is used if 2 are in the action


In a game... When the "done" button is pressed, there are 2 'if-statements': one brings you to the next level and the other returns you home. How can I make it so only one happens at a time? The way it works now, is both the winning and losing 'alertviews' pop up no matter if the user got it right or wrong. This is how it looks:

-(IBAction)done {

    if ([entry.text isEqualToString:sentance.text]) {

        UIAlertView *alert = [[UIAlertView alloc] 
                             initWithTitle:@"Cleared!" 
                             message:@""
                             delegate:nil 
                             cancelButtonTitle:@"Ok" 
                             otherButtonTitles: nil];
        [alert show];
        [alert release];

        seconds.text = @"5 Seconds";
    }

    if ([entry.text isEqualToString:entry.text]) {

        NSString *nssScore= [NSString stringWithFormat:@"Final Score: \n %i Points", Score];

        UIAlertView *alert = [[UIAlertView alloc]
                             initWithTitle:@"Nope! Wrong"
                             message:nssScore
                             delegate:nil
                             cancelButtonTitle:@"Ok"
                             otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
}

Solution

  • You can use else if condition.

    Like this :

    -(IBAction)done {
    
        if ([entry.text isEqualToString:sentance.text]) {
    
            UIAlertView *alert = [[UIAlertView alloc] 
                                  initWithTitle:@"Cleared!" 
                                  message:@""
                                  delegate:nil 
                                  cancelButtonTitle:@"Ok" 
                                  otherButtonTitles: nil];
            [alert show];
            [alert release];
    
            seconds.text = @"5 Seconds";
        }
        else if ([entry.text isEqualToString:entry.text]) {
    
            NSString *nssScore= [NSString stringWithFormat:@"Final Score: \n %i Points", Score];
    
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Nope! Wrong"
                                  message:nssScore
                                  delegate:nil
                                  cancelButtonTitle:@"Ok"
                                  otherButtonTitles: nil];
            [alert show];
            [alert release];
        }
    }
    

    or you can add a line of code in each block "return;"

    like this: