Using multiple NSUInteger enumerations as a method parameter

I am trying to create a method with a similar format for the setAutoresizingMask: NSView method. I want someone to be able to specify several values ​​that I declared in my enumeration (NSHeightSizable | NSWidthSizable), as in an autoresist mask. How can i do this?

+6
enums objective-c cocoa nsuinteger
source share
1 answer

First declare your flags in the header:

enum { AZApple = (1 << 0), AZBanana = (1 << 1), AZClementine = (1 << 2), AZDurian = (1 << 3) }; typedef NSUInteger AZFruitFlags; 

(1 << 0) to (1 << 3) represent single bits into integers that you can "mask" into and from an integer. For example, if you assume that NSUInteger is 32 bits, and someone selects both apple and durian, then the integer will look like this:

 0000 0000 0000 0000 0000 0000 0000 1001 | |- Apple bit |---- Durian bit 

Usually your method should accept 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 } } 
+19
source share

All Articles