[英]Objective-C: Check if using enum option
I have a custom object that is using a typedef enum. 我有一个使用typedef枚举的自定义对象。 If I set a few of the enum options for my object, how can I check to see if those are being used? 如果我为我的对象设置了一些枚举选项,我该如何检查它们是否被使用?
typedef enum {
Option1,
Option2,
Option3
} Options;
When creating my object I might use: 在创建我的对象时,我可能会使用:
myobject.options = Option1 | Option2;
How can I then later check which enum options were set? 我怎样才能稍后检查哪些枚举选项被设置? Such as: 如:
if (myobject.options == Option1) {
// Do something
}
if (myobject.options == Option2) {
// Do something
}
If you want to do bitwise logic for your options parameter, then you should define your enum so that each option only has a single bit set: 如果要为options参数执行按位逻辑,则应定义枚举,以便每个选项只设置一个位:
typedef enum {
Option1 = 1, // 00000001
Option2 = 1 << 1, // 00000010
Option3 = 1 << 2 // 00000100
} Options;
Then you set your options using the bitwise OR operator: 然后使用按位OR运算符设置选项:
myObject.options = Option1 | Option2;
and check which options have been set using the bitwise AND operator: 并使用按位AND运算符检查已设置的选项:
if(myObject.options & Option1) {
// Do something
}
You shouldn't use an enum for this, or at least not use the standard numbering. 您不应该使用枚举,或者至少不使用标准编号。
#define Option1 1
#define Option2 2
#define Option3 4
#define Option4 8
#define Option5 16
The values need to be powers of two, so you can combine them. 值必须是2的幂,因此您可以将它们组合在一起。 A value of 3 means options 1 + 2 are chosen. 值3表示选项1 + 2。 You wouldn't be able to make that distinction if 3 was a valid value for one of the other options. 如果3是其他选项之一的有效值,则无法进行区分。
I'd suggest to define the enum using NS_OPTIONS
. 我建议使用NS_OPTIONS
定义枚举。 This is the Apple recommended way to create such enums. 这是Apple推荐的创建此类枚举的方法。
typedef NS_OPTIONS(NSUInteger, Options) {
Options1 = 1 << 0,
Options2 = 1 << 1,
Options3 = 1 << 2,
};
Then, as it has already been said, you can assign values by doing: 然后,正如已经说过的那样,您可以通过执行以下操作来分配值:
myObject.options = Option1 | Option2;
and check them: 并检查他们:
if (myObject.options & Option1) {
// Do something
}
if ((myobject.options & Option1) == Option1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.