36

My problem is since an enum in objective-c essentially is an int value, I am not able to store it in a NSMutableArray. Apparently NSMutableArray won't take any c-data types like an int.

Is there any common way to achieve this ?

typedef enum 
{
    green,
    blue,
    red

} MyColors;


NSMutableArray *list = [[NSMutableArray alloc] initWithObjects:
                             green,
                             blue,
                             red,
                             nil];

//Get enum value back out
MyColors greenColor = [list objectAtIndex:0];
Oysio
  • 3,486
  • 6
  • 45
  • 54

6 Answers6

66

Wrap the enum value in an NSNumber before putting it in the array:

NSNumber *greenColor = [NSNumber numberWithInt:green];
NSNumber *redColor = [NSNumber numberWithInt:red];
NSNumber *blueColor = [NSNumber numberWithInt:blue];
NSMutableArray *list = [[NSMutableArray alloc] initWithObjects:
                             greenColor,
                             blueColor,
                             redColor,
                             nil];

And retrieve it like this:

MyColors theGreenColor = [[list objectAtIndex:0] intValue];

indragie
  • 18,002
  • 16
  • 95
  • 164
  • 1
    Generally this should be safe, but there are cases when it is not, since enums can be represented internally as a variety of different types. See this answer for an alternative http://stackoverflow.com/questions/1187112/cocoa-dictionary-with-enum-keys/1187901#1187901 – DougW Jul 20 '11 at 18:11
23

A modern answer might look like:

NSMutableArray *list = 
 [NSMutableArray arrayWithArray:@[@(green), @(red), @(blue)]];

and:

MyColors theGreenColor = ((NSInteger*)list[0]).intValue;
Alex Cio
  • 6,014
  • 5
  • 44
  • 74
Pat
  • 814
  • 8
  • 9
  • 2
    MyColors theGreenColor = ((NSInteger*)list[0]).intValue; Can be replaced by MyColors theGreenColor = (MyColors)[list[0] intValue]; – Haider Jan 30 '16 at 07:49
10

Macatomy's answer is correct. But instead of NSNumber I would suggest you use NSValue. That is its purpose in life.

nicktmro
  • 2,298
  • 2
  • 22
  • 31
7
NSMutableArray *corners = [[NSMutableArray alloc] initWithObjects:
                           @(Right), 
                           @(Top), 
                           @(Left), 
                           @(Bottom), nil];
Corner cornerType = [corner[0] intValue];
Alex Cio
  • 6,014
  • 5
  • 44
  • 74
Tai Le
  • 8,530
  • 5
  • 41
  • 34
2

You can wrap your enum values in a NSNumber object:

[NSNumber numberWithInt:green];
Thomas Zoechling
  • 34,177
  • 3
  • 81
  • 112
0

To go with NSNumber should be the right way normally. In some cases it can be useful to use them as NSString so in this case you could use this line of code:

[@(MyEnum) stringValue];
Alex Cio
  • 6,014
  • 5
  • 44
  • 74