Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef NS_OPTIONS check like UIViewAutoresizing

Tags:

ios

typedef

A short introduction to what I want to achieve with this:
I've a custom UIView where I want to make arrows visible, for example on bottom and left side. I thought it would be possible to do this the same way as UIViewAutoresizing does it.

So I created a similar typedef for my custom view:

typedef NS_OPTIONS(NSUInteger, Arrows) {
    ArrowNone      = 0,
    ArrowRight     = 1 << 0,
    ArrowBottom    = 1 << 1,
    ArrowLeft      = 1 << 2,
    ArrowTop       = 1 << 3
};

Also in my custom view header file, I added:

@property (nonatomic) Arrows arrows;

This all works and now I'm able to set the property:
customview.arrows = (ArrowBottom | ArrowLeft);

This returns 6.

Now's my question, how can check if my arrows property contains bottom and left? I tried:

if (self.arrows == ArrowLeft) {
    NSLog(@"Show arrow left");
}

This didn't do anything. Is there another way to check this?

like image 955
app_ Avatar asked Nov 04 '12 09:11

app_


3 Answers

The right way to check your bitmask is by decoding the value using the AND (&) operator as follows:

Arrows a = (ArrowLeft | ArrowRight);    
if (a & ArrowBottom) {
   NSLog(@"arrow bottom code here");    
}

if (a & ArrowLeft) {
   NSLog(@"arrow left code here");    
}    

if (a & ArrowRight) {
   NSLog(@"arrow right code here");    
}

if (a & ArrowTop) {
   NSLog(@"arrow top code here");    
}

This will print out in the console:

arrow left code here
arrow right code here
like image 167
fluxa Avatar answered Nov 07 '22 16:11

fluxa


To do a compound check you could use the following code:

if ((a & ArrowRight) && (a & ArrowTop)) {
       NSLog(@"arrow right and top code here");    
}
like image 41
rismay Avatar answered Nov 07 '22 15:11

rismay


The correct way to check for this value is to first bitwise AND the values and then check for equality to the required value.

Arrows a = (ArrowBottom | ArrowLeft);    
if (((a & ArrowBottom) == ArrowBottom) && ((a & ArrowLeft) == ArrowLeft)) {
    // arrow bottom-left
}

The following reference explains why this is correct and provides other insights into enumerated types.

Reference: checking-for-a-value-in-a-bit-mask

like image 28
NSWill Avatar answered Nov 07 '22 16:11

NSWill