iPhone SDK <<意思?

Noo*_*ath 4 iphone enums typedef

你好另一个愚蠢的简单问题 我注意到在Apple框架中的某些typedef中使用符号"<<"可以让任何人告诉我这意味着什么?:


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


编辑:好的,所以我现在明白你如何以及为什么要使用左移位,我的下一个问题是我将如何测试该值是否具有某个特征使用和if/then语句或switch/case方法?

zou*_*oul 7

这是一种创建易于混合的常量的方法.例如,您可以使用API​​订购冰淇淋,您可以选择任何香草,巧克力和草莓口味.你可以使用布尔值,但这有点重:

- (void) iceCreamWithVanilla: (BOOL) v chocolate: (BOOL) ch strawerry: (BOOL) st;
Run Code Online (Sandbox Code Playgroud)

解决这个问题的一个好方法是使用数字,您可以使用简单的添加来混合味道.假设香草为1,巧克力为2,草莓为4:

- (void) iceCreamWithFlavours: (NSUInteger) flavours;
Run Code Online (Sandbox Code Playgroud)

现在,如果数字的最右边位置设置,它就有香草味,另一个代表巧克力,右边的第三个位是草莓.例如,香草+巧克力将是1 + 2 = 3十进制(011二进制).

bitshift运算符x << y取左数(x)并将其位移位y.它是创建数字常量的好工具:

1 << 0 = 001 // vanilla
1 << 1 = 010 // chocolate
1 << 2 = 100 // strawberry
Run Code Online (Sandbox Code Playgroud)

瞧!现在,当你想用灵活的左边距和灵活的右边缘视图,您可以使用逐或混合标志:FlexibleRightMargin | FlexibleLeftMargin→交通1<<2 | 1<<0→交通100 | 001→交通101.在接收端,该方法可以使用逻辑掩盖有趣的位:

// 101 & 100 = 100 or 4 decimal, which boolifies as YES
BOOL flexiRight = givenNumber & FlexibleRightMargin;
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.