Q:

How to convert an enum to a byte array in Objective-C?

I have an enum and I want to pass one of its value to an Objective-C method expecting char * directly instead of creating another variable. What should I do?
e.g.
typedef enum { value1 = 0xAA, value2 = 0xBB, value3 = 0xCC } myValue;

NSMutableData *data = [[NSMutableData alloc] init];

// want to pass in the enum directly as char * but won't work

[data appendBytes:(char *){ value1 } length: 1];

// this will work, why? and is this the best way?

[data appendBytes:(char []){ value1 } length: 1];

A:

Your example of using (char[]){value1} to get a char* that points to value1 interpreted as a char is perfectly legitimate. Equivalent code might look like
char achar = value1;
[data appendBytes:&achar length:1];

But your (char[]){value1} is obviously one fewer lines of code, so I say go with that.

For any who are confused, (char[]){value1} is a compound literal. It's a way of constructing any sort of value, including aggregates, as an expression. In this particular case, it's constructing an array of chars, with the initializer containing one element, so this constructs a char[1], which then gets implicitly converted to a pointer when passed to the method. Interestingly, you can even take the address of compound literals (although the address is only going to be valid for the full expression in which the compound literal is found), so an equivalent in this case would be &(char){value1}.

