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?
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.
No, enums are supposed to be a complete static enumeration.
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()"[^].
You can change default values of enum elements during declaration (if necessary).
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.
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