开发者

why a line with logical NOT still does what a YES would do? [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

what does the exclamation mark in Objective C means in “if (![”

in my previous question I wasn't quite clear. What puzzles me is why in this line:

   if (![txtOperator.text isEqualToString: @"+"]) {
        int sum=a+b;
        [result setText: [NSString stringWithFormat:@"%d", sum]];

    } 

the operands are added and result displayed even though with the NOT operator it was not supposed to happen and when I add the following lines the calculator continues to do addition only doesn't matter what operator you put there.

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]];


    }


Let's look at what you're doing in detail here:

[txtOperator.text isEqualToString: @"-"]

You are checking if the txtOperator.text equals @"-".

So if it is -, it will return YES.

Otherwise NO.

Then you negate this statement:

![txtOperator.text isEqualToString: @"-"]

Now everything that is NOT a - will return YES.

And only the - will return NO.

Thus in your example, the if-clause is entered in every case but when the string matches. To check for string matches, leave out the NOT operator.


Some magick:

    NSString * a = nil;
    if (![a isEqualToString:@"A"]) {
    NSLog(@"A");
    }
    if (![a isEqualToString:@"B"]) {
    NSLog(@"B");
    }

Output:

    A
    B

Clear enough ? Be careful sending messages to nil.


Try imagining what will happen in your code. Say your operator is @"-". Now, on the first test

[txtOperator.text isEqualToString: @"+"]

Will return NO. But then, you negate this (!) so it becomes YES and your if condition succeeds.

If your operator is whatever thing (except @"+") it will always succeed on the first test. Now, if it's a @"+", the second test will succeed. Can you imagine why?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜