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
}
}
精彩评论