在Objective-C中选择一个随机枚举

Fog*_*ter 3 iphone enums typedef ios

我为我的iPhone应用程序创建了一个typedef枚举...

typedef enum {
    FirstType,
    SecondType,
    ThirdType
} type;
Run Code Online (Sandbox Code Playgroud)

仅仅为了测试,我希望能够从这些中选择随机类型.

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

Sul*_*han 19

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

EnumType randomType = (EnumType) (arc4random() % (int) EnumTypeMax);
Run Code Online (Sandbox Code Playgroud)

注意,EnumTypeMax等于3,不是4,这是正确的. EnumTypeMax被视为无效值.

另外,请在此处查看有关X-Macros解决方案的答案.

  • 在iOS 4.3及更高版本中,你应该使用`arc4random_uniform(EnumTypeMax)`而不是`arc4random()%EnumTypeMax` (3认同)