Iphone 在Objective-C中选择随机枚举

Iphone 在Objective-C中选择随机枚举,iphone,ios,enums,typedef,Iphone,Ios,Enums,Typedef,我已经为我的iPhone应用程序创建了typedef枚举 typedef enum { FirstType, SecondType, ThirdType } type; 只是为了测试,我想能够选择一个随机类型从这些 我打算使用arc4random()%4来做这件事,只是在它的位置使用int,但我想检查是否有更好的方法来做这件事 typedef enum { FirstType = 0, SecondType, ThirdType, Enu

我已经为我的iPhone应用程序创建了typedef枚举

typedef enum {
    FirstType,
    SecondType,
    ThirdType
} type;
只是为了测试,我想能够选择一个随机类型从这些

我打算使用
arc4random()%4
来做这件事,只是在它的位置使用int,但我想检查是否有更好的方法来做这件事

typedef enum {
    FirstType = 0,
    SecondType,
    ThirdType,
    EnumTypeMax
} EnumType;

EnumType randomType = (EnumType) (arc4random() % (int) EnumTypeMax);
请注意,
EnumTypeMax
等于
3
,而不是
4
,这是正确的。
EnumTypeMax
被视为无效值


另外,请参阅我关于X-Macros解决方案的答案。

太好了,谢谢。我只是想确认LastType从未被选中,但你们刚刚确认,对于我来说:D Plus已经过测试,并且可以正常工作。谢谢计时器用完时将接受。将
LastType
重命名为
EnumTypeMax
。在iOS 4.3及更高版本中,您应使用
arc4random\u统一(EnumTypeMax)
而不是
arc4random()%EnumTypeMax