Using Multiple NSUInteger enums as a parameter to a method
Asked Answered
P

1

6

I'm trying to make a method with a similar 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?

Professed answered 2/8, 2010 at 22:58 Comment(0)
R
19

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
    }
}
Reata answered 2/8, 2010 at 23:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.