<<客观的运算符?

时间:2011-12-28 16:25:35

标签: objective-c operators

我正在寻找一些东西并且进入这个枚举是苹果UITableViewCell.h。

我很抱歉,如果这是微不足道的,但我想知道/好奇这是什么意思。

我知道<<来自红宝石,但我真的不明白这个枚举?

enum {
    UITableViewCellStateDefaultMask                     = 0,
    UITableViewCellStateShowingEditControlMask          = 1 << 0,
    UITableViewCellStateShowingDeleteConfirmationMask   = 1 << 1
};

由于

顺便说一句 发现它是学习编码的好方法,我在一天内尝试进入对象列表的头文件。

沙尼

6 个答案:

答案 0 :(得分:25)

这些是位字段标志。使用它们是因为您可以使用按位OR运算符组合它们。例如,您可以将它们组合起来,如

(UITableViewCellStateShowingEditControlMask | UITableViewCellStateShowingDeleteConfirmationMask)

它们通过将一位设置为整数来工作。在这个例子中,二进制,

UITableViewCellStateShowingEditControlMask        = 0000 0001
UITableViewCellStateShowingDeleteConfirmationMask = 0000 0010

当它们被“或”在一起时,它们会产生0000 0011。然后框架知道这两个标志都已设置。

<<运算符是左移。它改变了二进制表示。所以1 << 1表示

0000 0001 shifted left by one bit = 0000 0010

1 << 2等于0000 0100

答案 1 :(得分:4)

它实际上是BItwise移位运算符

<<  Indicates the bits are to be shifted to the left.
>>  Indicates the bits are to be shifted to the right.

所以在你的陈述中,值1&lt;&lt; 0是1且1&lt;&lt; 1是2

答案 2 :(得分:3)

在C中使用枚举值中的按位移位运算符是一种常见技巧,允许您将枚举值与按位或运算符组合使用。

这段代码相当于

enum {
    UITableViewCellStateDefaultMask                     = 0,
    UITableViewCellStateShowingEditControlMask          = 1, // 01 in binary
    UITableViewCellStateShowingDeleteConfirmationMask   = 2  // 10 in binary
};

这允许您按位or两个或多个枚举常量

 (UITableViewCellStateShowingEditControlMask | UITableViewCellStateShowingDeleteConfirmationMask) // == 3 (or 11 in binary)

给出一个新常量,同时表示这两个事物。在这种情况下,单元格显示编辑控件和删除确认控件,或类似的东西。

答案 3 :(得分:1)

这就是bitshift运算符。这通常用于可能具有多个行为的对象(每个枚举都是行为)。

这是一个similar post,可以更好地澄清它。

答案 4 :(得分:1)

这些类型的运算符称为按位运算符,它对数字的位值进行操作。与其他的arithematic操作相比,这些操作非常快。

答案 5 :(得分:0)

这些操作数称为bitshift。 Bitshift操作数可能是首选    2个原因。       - 快速操作       - 一次使用多个bool值。

例如:1 <&lt;&lt; 2&lt; 2是左移;这意味着 1:0001, 2:0010

1&lt;&lt; 2这条线的意思是2应该留一个位。结果0010转移到0100

同样移位的值必须以1,2,4,8,16 ...

的顺序排序
typedef NS_OPTIONS(int, EntityEngineer) {
EntityEngineeriOS = 1 << 0,
EntityCategoryAndroid = 1 << 1,
EntityCategoryDB = 1 << 2,
EntityCategoryTeamLead = 1 << 16,};

现在,我们要在下面的行中检查多个布尔值,

char engineer = (EntityEngineeriOS | EntityCategoryAndroid);

char 0011 =(0001 | 0010);

if (engineer & EntityEngineeriOS) {
    NSLog(@"we are looking for a developer who can write objective c or java");
}

if (engineer & EntityCategoryDB) {
    NSLog(@"we are not looking for a DB manager");
}

结果:我们正在寻找能够编写目标c或java

的开发人员