Multiple Listing of Values ​​in Obj-C

The Cocoa and Cocoa Touch structures are listed as constants. I understand how to use it, except in one case, a case that you can pass as a parameter with multiple values ​​using the | . How in:

 pageControl.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin); 

The listing is declared as follows:

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

How can I determine for myself this type of enumeration (i.e. what does << mean) and how can I check the values ​​of multiples when passed as a parameter?

+46
enums objective-c iphone cocoa-touch cocoa
Nov 14 '10 at 4:11
source share
2 answers

<< - bit shift operator. So 1 << 2 says it translates the bit into two spaces.

Example:

In binary expression, the number 1 is:

 0001 

1 << 2 means the shift of all bits to the left 2 spaces, which leads to this value:

 0100 

or 4 .

Thus, the values ​​of each ENUM in your example are: 1, 2, 4, 8, 16, etc. They could precisely set each enumeration to these values. But since they use this enumeration for multiple values, binary values ​​make it more understandable:

 0001 0010 0100 1000 

so they write using bit shifts.

so if I OR ( | ) two of these values ​​together, for example FlexibleLeftMargin ( 0001 ) and FlexibleWidth ( 0010 ), I get the following value:

 0011 

Therefore, they use each bit as a flag, so they know that you have several values ​​set.

Now you can use the AND & operator to find out if a specific value is set.

 0010 & 0011 = 0010 

So you can do this to check if you have one of the enumerations:

 myenum = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin); if((myenum & UIViewAutoresizingFlexibleLeftMargin) == UIViewAutoresizingFlexibleLeftMargin) { // myenum has UIViewAutoresizingFlexibleLeftMargin set! } 

Hope this makes sense. For a more detailed explanation of bitwise operations, read this: Wikipedia ~ Bit Operators or search around for β€œ bit operators ”

+111
Nov 14 '10 at 4:26
source share

<< is the left shift operator, meaning moving the left value is N bits left. In this case, it sets one bit (bits 1, 2, 3, 4, 5) in the enumeration, which allows the bitwise operator OR ( | ) to combine the values.

0
Nov 14 '10 at 4:16
source share



All Articles