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];
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).
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.
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.
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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With