Frequently used symbol “|” in Objective-C

前端 未结 4 1287
清歌不尽
清歌不尽 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.

提交回复
热议问题