Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store enum values in a NSMutableArray

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]; 
like image 714
Oysio Avatar asked Mar 21 '10 15:03

Oysio


People also ask

How are enum values stored?

A standard enum is usually implemented as an int32, the compiler will handle your enum as a synonym of int32 . Once a list of values is created for a enumeration those values are stored as literals against their display name(access name given at the time of declaration of enum).

How are enums stored in rust?

All variants of an enum use the same amount of memory (in case of your Foo type, 16 bytes, at least on my machine). The size of the enum's values is determined by its largest variant ( One , in your example). Therefore, the values can be stored in the array directly.

How is enum stored in C?

Enumeration "values" aren't stored at all, as they are compile-time named constants. The compiler simply exchanges the use of an enumeration symbol, with the value of it. Also, the type of an enumeration value is of type int , so the exact size can differ.

Is enum 32 bit?

On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less. The GCC C compiler will allocate enough memory for an enum to hold any of the values that you have declared. So, if your code only uses values below 256, your enum should be 8 bits wide.


1 Answers

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

like image 50
indragie Avatar answered Sep 20 '22 17:09

indragie