typedef NS_OPTIONS check like UIViewAutoresizing

app_ picture app_ · Nov 4, 2012 · Viewed 7k times · Source

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?

Answer

fluxa picture fluxa · Dec 11, 2012

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