简体   繁体   中英

NS_OPTIONS matches

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.

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...) {

}

The correct way to check for this value is to first bitwise AND the values and then check for equality to the required value.

MyCellCorners cellCorners = MyCellCornerTopLeft | MyCellCornerTopRight;

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

The following reference explains why this is correct and provides other insights into enumerated types.

Reference: checking-for-a-value-in-a-bit-mask

I agree with NSWill. I recently had a similar issue with wrong comparison.

The right if statement should be:

if ((cellCorners & MyCellCornerTopLeft) == MyCellCornerTopLeft){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM