在iOS中使用逻辑运算符(OR / AND,...)

时间:2014-12-02 13:53:14

标签: ios objective-c if-statement expression

我是编程的新手, 我需要在if条件中验证几个表达式,当它们都返回true时,只需要做一些工作。

我知道我可以通过使用逻辑运算符来做到这一点,但我不清楚逻辑运算符的工作原理。

对此的任何帮助都将非常感激。

先谢谢。

3 个答案:

答案 0 :(得分:4)

与许多编程语言一样,有逻辑运算符可用。

您好像在寻找AND运营商:

if (conditionA && conditionB) {
  // conditional code
}

有关详细信息,请参阅Wikipedia: Logical operators in C

答案 1 :(得分:4)

使用逻辑运算符是最好的,多个条件。

例如

int firstValue = 10;     int sencondValue = 16;

// OR operator , retursn TRUE is any of given condtion is true.
if (firstValue==10 || sencondValue==13 || firstValue>=5) {
    NSLog(@"True");
}
else
{

NSLog(@"False");


}
//above are 3 condtions in one statement , if any condition is true , result is true

// AND operator , retursn TRUE is all of given condtion are true  and flase if any on the given conditions are false.

if (firstValue==10 && sencondValue==13 && firstValue>=5) {
    NSLog(@"True");
}
else
{

    NSLog(@"False");


}

答案 2 :(得分:1)

使用短路逻辑和运算符......

示例1。

if (1 == 1 && 2 == 2) {
    // statements that will always execute
} 

示例2

boolean firstCondition = YES;
boolean secondCondition = NO;
boolean thirdCondition = YES;

if (firstCondition && secondCondition && thirdCondition) {
    // As secondCondition is false this will never execute (and thirdCondition will never be evaluated)
}

使用逻辑和运算符,只有在第一个和第二个条件求值为true时,才会执行花括号内的语句。此外,如果第一个条件为假,则甚至不会评估第二个条件,因此名称会短路。