0

what is the proper syntax for putting together and & or statements?

I am trying to implement some code to validate the data a user is inputting. I have a segmented control, a text view and a next page button. To advance to the next view controller the user must choose "yes" or "no" on the segmented control and if yes is selected they must enter some text into the text view.

- (IBAction)nextPageButton:(UIBarButtonItem *)sender {

if (weatherDelayString == nil || ([weatherDelayString isEqual: @"YES"] && weatherDelayTextView.text == nil)) {
    NSLog(@"nothing selected");
}else{
    vc7Signature *vc7 = [[vc7Signature alloc]initWithNibName:nil bundle:nil];
[self presentViewController:vc7 animated:YES completion:nil];
}}

Could someone clarify the syntax required to implement this logic?

  • What language are you using? – Cramer May 14 '13 at 04:36
  • Objective C (but this is my first time writing these kinds of statements). The || worked correctly on in another location in my project, but I have not been able to get || and && working together. – BBringardner May 14 '13 at 04:40

3 Answers3

1

Put brackets around each decision so that it's absolutely clear. So, you currently have

A || B && C

whereas you should put in

(A || B) && C

or

A || (B && C)

I'll leave it up to you to decide which is best for your application

Cramer
  • 1,785
  • 1
  • 12
  • 20
  • While my answer answers the question directly, Michael Dautermann's answer is better (more easily readable) code. – Cramer May 14 '13 at 04:46
1

Why not de-mangle / de-tangle your code to get rid of some of the AND & OR cases. I can do this with one single AND:

- (IBAction)nextPageButton:(UIBarButtonItem *)sender {

    if ([weatherDelayString isEqual: @"YES"] && ([weatherDelayTextView.text length] > 0))
    {
        vc7Signature *vc7 = [[vc7Signature alloc]initWithNibName:nil bundle:nil];
        [self presentViewController:vc7 animated:YES completion:nil];
    } else {
        NSLog(@"the YES / NEXT condition I want the users to have to go forward isn't selected");
    }
}

Which hopefully is easier to read than a OR plus a nested AND conditional.

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • Thanks for the help. Actually your line [weatherTextView.text length ]>0 did the trick. I did not know about length and I saw that I made an error in my code. Thanks! – BBringardner May 14 '13 at 04:54
0

Use this one,,,

- (IBAction)nextPageButton:(UIBarButtonItem *)sender 
{
        if ((weatherDelayString == nil || [weatherDelayString isEqual: @"YES"]) && weatherDelayTextView.text == nil)
        {
            NSLog(@"nothing selected");
        }
        else
        {
            vc7Signature *vc7 = [[vc7Signature alloc]initWithNibName:nil bundle:nil];
            [self presentViewController:vc7 animated:YES completion:nil];
        }
}
Dharmbir Singh
  • 17,485
  • 5
  • 50
  • 66