4

I need to write a method like this:

-(void)doStuff:(int)options;

Based in the a typedef enum like this:

typedef enum
{
    FirstOption,
    SecondOption,
    ThirdOption
} MyOptions

What I need to to do in order to be able to call the method in this way (i.e. calling the method with more than one option "enabled":

[self doStuff:(FirstOption | ThirdOption)];

Do I need to setup the typedef enum differently? And how I check the options received in the method, a simple if (options == ...)?

Natan R.
  • 5,141
  • 1
  • 31
  • 48

2 Answers2

4

What you call for is a bit array. Define your options like this:

enum MyOptions
{
    FirstOption = 0x01, // first bit
    SecondOption = 0x02, // second bit
    ThirdOption = 0x04, // third bit
    ... = 0x08 ...
};

Combine the options like you suggested, with |, and test for them with & (options & SecondOption).

- (void) doStuff: (MyOptions) options
{
    if ( options & FirstOption )
    {
        // do something fancy
    }

    if ( options & SecondOption )
    {
        // do something awesome
    }

    if ( (options & SecondOption) && ( options & ThirdOption) )
    {
        // do something sublime
    }
}
1

I'm no expert at Obj-C, but in other languages I would use flags. If each value is a power of two, then it will have only one bit set for that value. You can use that bit as a bool for a particular option.

FirstOption = 1
SecondOption = 2
ThirdOption = 4

FirstAndThird = FirstOption | ThirdOption; // Binary Or sets the bits

// Binary And checks the bits
IsFirst = FirstAndThird & FirstOption == FirstOption; // is true
IsSecond = FirstAndThird & SecondOption == SecondOption; // is false
IsThird = FirstAndThird & ThirdOption == ThirdOption; // is true

This question may also be of use.

Community
  • 1
  • 1
Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188