Goal C - How to get two ints in one parameter

I need to write a method like this:

-(void)doStuff:(int)options; 

Based on the typedef enumeration as follows:

 typedef enum { FirstOption, SecondOption, ThirdOption } MyOptions 

What I need to do to be able to call the method this way (i.e., call the method with several parameters enabled:

 [self doStuff:(FirstOption | ThirdOption)]; 

Does typedef enum need to be configured differently? And how do I check the parameters obtained in the method, a simple if (options == ...) ?

+4
source share
2 answers

You are calling an array bit. Define your parameters as follows:

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

Combine the options you proposed with | and test 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 } } 
+4
source

I am not an expert in Obj-C, but in other languages ​​I would use flags. If each value is two, then only one bit will be set for this value. You can use this bit as bool for a specific 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 helpful.

+1
source

All Articles