What does the exclamation mark mean in an Objective-C if statement?

前端 未结 7 963
無奈伤痛
無奈伤痛 2020-12-11 09:57

I am wondering what the exclamation mark in if(!anObject) means.

相关标签:
7条回答
  • 2020-12-11 10:22

    It's a C operator, simply meaning "not". So !YES == NO and !NO == YES are both true statements. if (![txtOperator.text isEqualToString: @"+"]), for example, checks to see if txtOperator.text is NOT equal to @"+".

    0 讨论(0)
  • 2020-12-11 10:30

    It is the boolean NOT operator also called negation.

    !true == false;
    !false == true;
    
    0 讨论(0)
  • 2020-12-11 10:30

    If it always adds, then your string is never "+".

    The logic as you have it will always add a+b unless the txtOperator.txt is exactly equal to @"+".

    Interestingly if you did pass a plus it would always subtract, only the first two cases would ever be hit because if the first was not true the second always would be.

    Basically, take out all the "!"....

    0 讨论(0)
  • 2020-12-11 10:30

    You should not add "!" to the start of condition in "if". Your code says that if operator's text is not +, then add and so on. Your code should be like this;

    -(IBAction) calculateResult {

    a = [txtOperand1.text intValue];
    b = [txtOperand2.text intValue];
    
    if ([txtOperator.text isEqualToString: @"+"]) {
        int sum=a+b;
        [result setText: [NSString stringWithFormat:@"%d", sum]];
    
    } else if ([txtOperator.text isEqualToString: @"-"]) {
        int sum=a-b;
        [result setText: [NSString stringWithFormat:@"%d", sum]];
    }
    else if  ([txtOperator.text isEqualToString: @"/"]) {
        int sum=a/b;
        [result setText: [NSString stringWithFormat:@"%d", sum]];
    
    }
    else if  ([txtOperator.text isEqualToString: @"*"]) {
        int sum=a * b;
        [result setText: [NSString stringWithFormat:@"%d", sum]];
    
    
    }
    else [result setText:@"nothing"]; 
    
    0 讨论(0)
  • 2020-12-11 10:31

    So what about its use in a statement like this (taken from an online class example):

    (In this example, a button is pressed and upon clicking the button, the code below "toggles" between the Default state and the Selected state):

    - (IBAction)flipCard:(UIButton *)sender
    {
        sender.selected = !sender.isSelected;
    }
    
    0 讨论(0)
  • 2020-12-11 10:39

    That is the Logical NOT operator, i.e., if( thisThisIsNotTrue ) { doStuff }.

    0 讨论(0)
提交回复
热议问题