问题
I am wondering what the exclamation mark in if(!anObject)
means.
回答1:
It is the boolean NOT operator also called negation.
!true == false;
!false == true;
回答2:
That is the Logical NOT operator, i.e., if( thisThisIsNotTrue ) { doStuff }
.
回答3:
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 @"+".
回答4:
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 "!"....
回答5:
As everyone has mention is just a NOT operator, what I believe might have confused you is the brackets [], Objective C, comes from a language called small talk, that uses a send message approach to objects, the brackets are used to send that message. The messages are really functions.
回答6:
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"];
回答7:
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;
}
来源:https://stackoverflow.com/questions/6576413/what-does-the-exclamation-mark-mean-in-an-objective-c-if-statement