Is is possible to set an NS_OPTION as a value in an NSMutableDictionary?

1.1k views Asked by At

I'm trying to set up a dictionary of rules; the keys are strings, and I'd love to set up the values to be bitmaps.

I'm using NS_OPTION to declare items as such :

typedef NS_OPTIONS(NSInteger, PermittedDirection) {
  LeftDirection = 1 << 0,
  RightDirection = 1 << 1
};

typedef NS_OPTIONS(NSInteger, PermittedSize) {
  SmallSize = 1 << 0,
  MediumSize = 1 << 1,
  LargeSize = 1 << 2
};

I have my rules dictionary defined as such :

 @property (atomic, strong) NSMutableDictionary * rules;

later I instantiate it as such :

 self.rules = [[NSMutableDictionary alloc] init];

later I try to add the bitmask (as below) and get an error since an enum isn't a pointer to an object :

    PermittedSize size = SmallSize | LargeSize;
    [self.rules setObject:size forKey:ALLOWED_FISH_SIZE];

is there an easy way to wrap these somehow without losing the ability to use the bitmask later on when I retrieve the values?

1

There are 1 answers

0
Marcelo On BEST ANSWER

You can wrap it on an NSNumber by using:

PermittedSize size = SmallSize | LargeSize;
self.rules[ALLOWED_FISH_SIZE] = @(size);

Then, when you retrieve it, just unbox the value:

PermittedSize size = (PermittedSize) [self.rules[ALLOWED_FISH_SIZE] integerValue];