2

A << operator is used in UITableViewCell, as listed below:

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

I had been to this post << operator in objective c enum? but still not clear about the use of << operator.

The same above mentioned Enum and be written as mentioned below, then why is it so, they have used << operator?

enum {
     UITableViewCellStateDefaultMask                     = 0,
     UITableViewCellStateShowingEditControlMask          = 1,
     UITableViewCellStateShowingDeleteConfirmationMask   = 2
};
Community
  • 1
  • 1
NNikN
  • 3,720
  • 6
  • 44
  • 86

2 Answers2

2

The post you have linked explains why quite clearly. The << operator in C shifts numbers left by the specified number of bits. By shifting a 1 into each column, it is easy to see that the enum options can be bitwise ORed together. This allows the enum options to be combined together using the | operator and held in a single integer. This would not work if the enum declaration was as follows:

enum {
     UITableViewCellStateDefaultMask                     = 0, (= 00 in binary)
     UITableViewCellStateShowingEditControlMask          = 1, (= 01 in binary)
     UITableViewCellStateShowingDeleteConfirmationMask   = 2, (= 10 in binary)
     UITableViewCellStateThatIJustMadeUpForThisExample   = 3  (= 11 in binary)
};

As 3 = 11 in binary, it is not possible to know from a single integer if you have the state UITableViewCellStateThatIJustMadeUpForThisExample or UITableViewCellStateShowingEditControlMask ORed with UITableViewCellStateShowingDeleteConfirmationMask.

Tark
  • 5,153
  • 3
  • 24
  • 23
2

The enum values give names to bits that are to be used in a bitmask. The bits in a bitmask by value are 1, 2, 4, 8, 16, ... (the powers of two). These values can be more clearly shown using the expressions (1<<0, 1<<1, 1<<2, 1<<3) -- i.e,. 1 shifted to the left by 0, 1, ... places. It's clearly and less error prone than listing the powers of 2 as decimal constants.

When you use the values, they are normally combined using a bitwise-OR operation ('|'). The goal is to specify zero or more bits, each of which has a specific meaning. Using a bitmask allows you to specify them independently but compactly. You may wish to read more on bitmasks for more details and examples.

Art Swri
  • 2,799
  • 3
  • 25
  • 36