Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change enum values at runtime?

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?

like image 687
i_raqz Avatar asked Apr 24 '12 20:04

i_raqz


People also ask

Can we change enum values in runtime?

An Enum can only be changed in Edit Mode. If you try to change it in runtime, you will get the error. You can't edit an Enum in runtime. An alternative is to use VI Server; you can refer the example from the forum Programmatically Add Elements to Enum / Ring.

Can we add new enumeration value by runtime?

No, enums are supposed to be a complete static enumeration.

Can you change enum values C++?

You cannot modify at runtime a C++ enum. However you may design a class miming the enum behaviour and supporting the requested features (see, for instance, this CodeProject 's article: "Typesafe C++ Enum with ToString() and FromString()"[^].

Can we change enum value in C?

You can change default values of enum elements during declaration (if necessary).


1 Answers

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.

like image 113
Richard J. Ross III Avatar answered Sep 30 '22 06:09

Richard J. Ross III