Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

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];
        }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top