20

I am trying to implement the following typedef

typedef NS_OPTIONS (NSInteger, MyCellCorners) {
    MyCellCornerTopLeft,
    MyCellCornerTopRight,
    MyCellCornerBottomLeft,
    MyCellCornerBottomRight,
};

and correctly assign a value with

MyCellCorners cellCorners = (MyCellCornerTopLeft | MyCellCornerTopRight);

when drawing my cell, how can I check which of the options match so I can correctly draw it.

4

3 回答 3

53

Use bit masking:

typedef NS_OPTIONS (NSInteger, MyCellCorners) {
    MyCellCornerTopLeft = 1 << 0,
    MyCellCornerTopRight = 1 << 1,
    MyCellCornerBottomLeft = 1 << 2,
    MyCellCornerBottomRight = 1 << 3,
};

MyCellCorners cellCorners = MyCellCornerTopLeft | MyCellCornerTopRight;

if (cellCorners & MyCellCornerTopLeft) {
    // top left corner set
}

if (etc...) {

}
于 2012-12-11T06:21:59.077 回答
26

检查此值的正确方法是先将这些值按位与,然后检查是否与所需值相等。

MyCellCorners cellCorners = MyCellCornerTopLeft | MyCellCornerTopRight;

if ((cellCorners & MyCellCornerTopLeft) == MyCellCornerTopLeft) {
    // top left corner set
}

以下参考资料解释了为什么这是正确的,并提供了对枚举类型的其他见解。

参考:检查位掩码中的值

于 2015-04-27T00:43:43.283 回答
1

我同意 NSWill 的观点。我最近遇到了类似的错误比较问题。

正确的 if 语句应该是:

if ((cellCorners & MyCellCornerTopLeft) == MyCellCornerTopLeft){
于 2015-11-13T11:31:52.770 回答