Change enum values at runtime?

i_raqz picture i_raqz · Apr 24, 2012 · Viewed 12.5k times · Source

Is there a way to assign values to enums during runtime in objective c? I have several enums and want each of the enum to have certain value. The values could be read from a xml file. Is there a way to do this?

Answer

Richard J. Ross III picture Richard J. Ross III · Apr 24, 2012

Unfortunatley, @Binyamin is correct, you cannot do this with an enum. For this reason, I usually do the following in my projects:

// in .h
typedef int MyEnum;

struct {
    MyEnum value1;
    MyEnum value2;
    MyEnum value3;
} MyEnumValues;

// in .m
__attribute__((constructor))
static void initMyEnum()
{
    MyEnumValues.value1 = 10;
    MyEnumValues.value2 = 75;
    MyEnumValues.value3 = 46;
}

This also has the advantage of being able to iterate through the values, which is not possible with a normal enum:

int count = sizeof(MyEnumValues) / sizeof(MyEnum);
MyEnum *values = (MyEnum *) &MyEnumValues;

for (int i = 0; i < count; i++)
{
    printf("Value %i is: %i\n", i, values[i]);
}

All in all, this is my preferred way to do enums in C.