开发者

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

开发者 https://www.devze.com 2023-03-17 18:38 出处:网络
I am wondering what the exclamation mark in if(!anObject) mean开发者_开发百科s.It is the boolean NOT operator also called negation.

I am wondering what the exclamation mark in if(!anObject) mean开发者_开发百科s.


It is the boolean NOT operator also called negation.

!true == false;
!false == true;


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


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 @"+".


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 "!"....


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.


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


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

精彩评论

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

关注公众号