0

我有一个简单的函数,它返回NSNumbers 的原始总和,但如果它们是 -1,则不计算它们:

- (NSInteger)total {
    return [[self obj1] integerValue] == -1 ? 0 : [[self obj1] integerValue] + 
           [[self obj2] integerValue] == -1 ? 0 : [[self obj2] integerValue] +
           [[self obj3] integerValue] == -1 ? 0 : [[self obj3] integerValue];
}

在这种情况下total将始终返回 0。

但如果我这样写:

- (NSInteger)total {
    NSInteger ret = 0;
    ret += [[self obj1] integerValue] == -1 ? 0 : [[self obj1] integerValue];
    ret += [[self obj2] integerValue] == -1 ? 0 : [[self obj2] integerValue];
    ret += [[self obj3] integerValue] == -1 ? 0 : [[self obj3] integerValue];
    return ret;
}

total将返回正确的值。

我不喜欢以一种方式写它而不是另一种方式,但我看不出第一种方式有什么问题。

4

1 回答 1

4

Operator precedence. The ternary operator has the third lowest precedence in C, so the addition is evaluated before it could get to the conditional part. Use parentheses:

return ([[self obj1] integerValue] == -1 ? 0 : [[self obj1] integerValue]) + 
       ([[self obj2] integerValue] == -1 ? 0 : [[self obj2] integerValue]) +
       ([[self obj3] integerValue] == -1 ? 0 : [[self obj3] integerValue]);
于 2013-01-29T20:06:33.473 回答