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];

6 Answers 6

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];

Sign up to request clarification or add additional context in comments.

1 Comment

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 stackoverflow.com/questions/1187112/…
23

A modern answer might look like:

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

and:

MyColors theGreenColor = ((NSInteger*)list[0]).intValue;

1 Comment

MyColors theGreenColor = ((NSInteger*)list[0]).intValue; Can be replaced by MyColors theGreenColor = (MyColors)[list[0] intValue];
10

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

Comments

7
NSMutableArray *corners = [[NSMutableArray alloc] initWithObjects:
                           @(Right), 
                           @(Top), 
                           @(Left), 
                           @(Bottom), nil];
Corner cornerType = [corner[0] intValue];

Comments

2

You can wrap your enum values in a NSNumber object:

[NSNumber numberWithInt:green];

Comments

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.