sexta-feira, 20 de julho de 2012

Enum - Bit Operators


enum {
    UIViewAutoresizingNone                 = 0,
    UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,
    UIViewAutoresizingFlexibleWidth        = 1 << 1,
    UIViewAutoresizingFlexibleRightMargin  = 1 << 2,
    UIViewAutoresizingFlexibleTopMargin    = 1 << 3,
    UIViewAutoresizingFlexibleHeight       = 1 << 4,
    UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
typedef NSUInteger UIViewAutoresizing;







<< is the bitshift operator. So 1 << 2 tells it to shift the bit two spaces over.
Example:
In binary the number 1 is:
0001
1 << 2 means to shift all the bits to the left 2 spaces, which results in this value:
0100
or 4.
So the values of each ENUM in your example is, 1, 2, 4, 8, 16, etc. They could have just as well set each enum to those values. But since they use that enum for multiple values, the binary values makes it more clear:
0001
0010
0100
1000
so they wrote using the bit shifts.
so if I OR (|) two of those values together, for example FlexibleLeftMargin (0001) and FlexibleWidth (0010), I would get the following value:
0011
So they use each bit as a flag so they know you have multiple values set.
You can now use the AND operator & to figure out if you have a specific value set.
0010 & 0011 = 0010
So you could do this to check if you have one of enums set:
myenum = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin);
if((myenum & UIViewAutoresizingFlexibleLeftMargin) == UIViewAutoresizingFlexibleLeftMargin) {
  // myenum has UIViewAutoresizingFlexibleLeftMargin set!
}
Fonte: http://stackoverflow.com/questions/4176149/multiple-value-enum-in-obj-c