在运行时更改枚举值? [英] Change enum values at runtime?

查看:54
本文介绍了在运行时更改枚举值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以在运行时在目标c中为枚举分配值?我有几个枚举,并希望每个枚举都具有一定的价值.可以从xml文件中读取值.有办法吗?

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?

推荐答案

不幸的是,@ Binyamin是正确的,您不能使用枚举来做到这一点.因此,我通常在项目中执行以下操作:

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]);
}

总而言之,这是我在C中进行枚举的首选方式.

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

这篇关于在运行时更改枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆