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

查看:25
本文介绍了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?

推荐答案

<< 是位移运算符.所以 1 <<2 告诉它把位移动两个空格.

<< 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.

所以,如果我 OR (|) 这些值中的两个,例如 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

因此他们将每一位用作标志,以便他们知道您设置了多个值.

So they use each bit as a flag so they know you have multiple values set.

您现在可以使用 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!
}

希望这是有道理的.有关按位运算的更详细解释,请阅读:Wikipedia ~ Bit Operators 或搜索关于位运算符"

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天全站免登陆