Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Check if using enum option

I have a custom object that is using a typedef enum. If I set a few of the enum options for my object, how can I check to see if those are being used?

typedef enum {
    Option1,
    Option2,
    Option3
} Options;

When creating my object I might use:

myobject.options = Option1 | Option2;

How can I then later check which enum options were set? Such as:

if (myobject.options == Option1) {
  // Do something
}

if (myobject.options == Option2) {
  // Do something
}
like image 924
Nic Hubbard Avatar asked Aug 22 '11 22:08

Nic Hubbard


1 Answers

If you want to do bitwise logic for your options parameter, then you should define your enum so that each option only has a single bit set:

typedef enum {
    Option1 = 1,       // 00000001
    Option2 = 1 << 1,  // 00000010
    Option3 = 1 << 2   // 00000100
} Options;

Then you set your options using the bitwise OR operator:

myObject.options = Option1 | Option2;

and check which options have been set using the bitwise AND operator:

if(myObject.options & Option1) {
    // Do something
}
like image 62
glorifiedHacker Avatar answered Oct 04 '22 21:10

glorifiedHacker