Change enum values at runtime?

大憨熊 提交于 2021-01-21 04:46:10

问题


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?


回答1:


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.




回答2:


No, enums information is erased at compile time.



来源:https://stackoverflow.com/questions/10305315/change-enum-values-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!