Frequently used symbol “|” in Objective-C

前端 未结 4 1286
清歌不尽
清歌不尽 2020-12-11 10:11
self.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleWidth;

The source code is shown above. Wonder what the symbol \"|

相关标签:
4条回答
  • 2020-12-11 10:29

    In short: that is a bitwise OR operation.

    It is tipically used in generating bitmasks.

    With this operation you can combine flags into on binary number.

    For example: possible flags for UIViewAutoresizing are:

    enum {
       UIViewAutoresizingNone                 = 0,           // = 0b 0000 0000 =  0
       UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,      // = 0b 0000 0001 =  1
       UIViewAutoresizingFlexibleWidth        = 1 << 1,      // = 0b 0000 0010 =  2
       UIViewAutoresizingFlexibleRightMargin  = 1 << 2,      // = 0b 0000 0100 =  4
       UIViewAutoresizingFlexibleTopMargin    = 1 << 3,      // = 0b 0000 1000 =  8
       UIViewAutoresizingFlexibleHeight       = 1 << 4,      // = 0b 0001 0000 = 16
       UIViewAutoresizingFlexibleBottomMargin = 1 << 5       // = 0b 0010 0000 = 32
    };
    typedef NSUInteger UIViewAutoresizing;
    

    Statement:

    self.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleWidth;
    

    is esentially the same as:

    self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    

    (since both operands are the same).

    If you would ask about:

    self.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    

    this would set self.autoresizingMask to:

    (1<<1)|(1<<4)=(0b 0000 0010)|(0b 0001 0000)=0b 0001 0010 = 9
    

    Bitwise OR is not to be confused by Logical OR used with simple true/false algebra.

    There is some relation between the two (bitwise or can be understood as a logical or between the bits on the same position) but that is about it.

    0 讨论(0)
  • 2020-12-11 10:37

    The | character denotes an inclusive-or bitwise operation. which operates under the premise with matching the bitstrings of two objects.

    if you have a bitstring 1101 and another 1001 the inclusive or of the two would produce 1011. Basically if the current bit is the same in both strings then a 1 is outputted in its place otherwise a 0 is.

    0 讨论(0)
  • 2020-12-11 10:42

    | is the bitwise OR operator in C (and therefore in Objective-C).

    See http://en.m.wikipedia.org/wiki/Bitwise_operations_in_C

    In the context you asked about, it's being used to combine two flag values.

    0 讨论(0)
  • 2020-12-11 10:49

    That is a bitwise OR operation, maybe this can help you : Bitwise operation

    0 讨论(0)
提交回复
热议问题