开发者

Using Multiple NSUInteger enums as a parameter to a method

I'm trying to make a method with a sim开发者_StackOverflow社区ilar format to the setAutoresizingMask: method of NSView. I want to have someone be able to specify multiple values that i declared in my enum (NSHeightSizable | NSWidthSizable) like in autoresizing mask. How can I do this?


First, declare your flags in a header:

enum
{
    AZApple = (1 << 0),
    AZBanana = (1 << 1),
    AZClementine = (1 << 2),
    AZDurian = (1 << 3)
};

typedef NSUInteger AZFruitFlags;

The (1 << 0) through to (1 << 3) represent single bits in an integer that you can “mask” in and out of an integer. For example, assuming NSUInteger is 32-bits, and someone has chosen both apple and durian, then the integer would look like this:

0000 0000 0000 0000 0000 0000 0000 1001
                                   |  |- Apple bit
                                   |---- Durian bit

Typically your method needs to take an unsigned integer argument:

- (void) doSomethingWithFlags:(AZFruitFlags) flags
{
    if (flags & AZApple)
    {
        // do something with apple

        if (flags & AZClementine)
        {
            // this part only done if Apple AND Clementine chosen
        }
    }

    if ((flags & AZBanana) || (flags & AZDurian))
    {
        // do something if either Banana or Durian was provided
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜