在if条件中使用三元运算 - 目标C.

时间:2017-01-30 04:59:51

标签: ios objective-c

我试图检查if numberOfItemsPerSection在if条件下是否大于3。它总是返回true。然后我决定调试。

indexPath.row如何等于1和numberOfItemsPerSection = 20并且它会进入if条件。

使用以下三元运算符我做错了什么?

if(indexPath.row == (numberOfItemsPerSection > 3) ? (numberOfItemsPerSection-4) : numberOfItemsPerSection)
{


}

3 个答案:

答案 0 :(得分:4)

使用括号来解析优先级。通过以下方式更改条件。用括号覆盖你的turnery条件。它将首先解析turnery操作员,然后将它与indexPath.row进行比较。

if(indexPath.row == ((numberOfItemsPerSection > 3) ? (numberOfItemsPerSection-4) : numberOfItemsPerSection))

答案 1 :(得分:1)

你可以写:

if (indexPath.row == (numberOfItemsPerSection > 3 ? numberOfItemsPerSection - 4 : numberOfItemsPerSection)) { ... }

或者如果你不想伤害你的眼睛:

BOOL desiredRow = numberOfItemsPerSection > 3 ? numberOfItemsPerSection - 4 : numberOfItemsPerSection;
if (indexPath.row == desiredRow) { ... }

答案 2 :(得分:1)

NSInteger desiredRow = numberOfItemsPerSection > 3 ? (numberOfItemsPerSection-4) : numberOfItemsPerSection;
if(indexPath.row == desiredRow) { ... // do your coding }
相关问题