Obj-C中的多值枚举 [英] Multiple value enum in Obj-C

查看:342
本文介绍了Obj-C中的多值枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Cocoa和Cocoa Touch框架中,枚举被用作常量。我理解如何使用它,除非在一种情况下,您可以作为参数多个值与 | 运算符传递。像:

In the Cocoa and Cocoa Touch frameworks, enums are used as constant. I understand how to use it except in one case, the case you can pass as a parameter multiple value with the | operator. Like in :

pageControl.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin);

枚举声明如下:

enum {
    UIViewAutoresizingNone                 = 0,
    UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,
    UIViewAutoresizingFlexibleWidth        = 1 << 1,
    UIViewAutoresizingFlexibleRightMargin  = 1 << 2,
    UIViewAutoresizingFlexibleTopMargin    = 1 << 3,
    UIViewAutoresizingFlexibleHeight       = 1 << 4,
    UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
typedef NSUInteger UIViewAutoresizing;

如何定义自己的这种类型的枚举(即< ; 表示),以及如何作为参数传递时检查多个值?

How can I define myself this type of enum (i.e. what << means) and how can I check for multiples values when passed as a parameter?

推荐答案

code><< 是bitshift运算符。因此 1<<

<< is the bitshift operator. So 1 << 2 tells it to shift the bit two spaces over.

示例:

在二进制数字 1 是:

0001

1< 2 表示将所有位移到左侧2个空格,得到此值:

1 << 2 means to shift all the bits to the left 2 spaces, which results in this value:

0100

4

因此,您的示例中每个ENUM的值为1,2,4,8,16等。他们可以设置每个枚举值到这些值。但由于他们使用该枚举的多个值,二进制值使它更清楚:

So the values of each ENUM in your example is, 1, 2, 4, 8, 16, etc. They could have just as well set each enum to those values. But since they use that enum for multiple values, the binary values makes it more clear:

0001
0010
0100
1000

,因此他们使用位移位写入。

so they wrote using the bit shifts.

所以如果我或者( | )两个值一起,例如 FlexibleLeftMargin 0001 )和FlexibleWidth( 0010 ),我会得到以下值:

so if I OR (|) two of those values together, for example FlexibleLeftMargin (0001) and FlexibleWidth (0010), I would get the following value:

0011

现在可以使用AND运算符& 找出您是否有特定的值集。

You can now use the AND operator & to figure out if you have a specific value set.

0010 & 0011 = 0010

因此,您可以检查是否设置了一个枚举:

So you could do this to check if you have one of enums set:

myenum = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin);
if((myenum & UIViewAutoresizingFlexibleLeftMargin) == UIViewAutoresizingFlexibleLeftMargin) {
  // myenum has UIViewAutoresizingFlexibleLeftMargin set!
}

希望这很有意义。
有关逐位操作的更多说明,请阅读:维基百科〜位操作符或搜索位运算符

Hopefully this makes sense. For a more thurough explanation on bitwise operations read this: Wikipedia ~ Bit Operators or search around for "bit operators"

这篇关于Obj-C中的多值枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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