Search code examples
objective-ciosnscalendar

Please explain the use of bitwise operator OR in NSDateComponents?


I can't seem to find an answer to this. Here nor documentation. Maybe I'm not sure what I should be looking for?

unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;

From my understanding those should be logical bitwise operators for "OR"

How do they work in this situation?


Solution

  • bitwise operators used like this is a way of setting multiple boolean flags in one variable, called a bitmask

    so if

    FlagA = 1 << 3; //binary = 1000
    FlagB = 1 << 2; //binary = 0100
    FlagC = 1 << 1; //binary = 0010
    FlagD = 1 << 0; //binary = 0001
    

    and i set

    myFlag = FlagA | FlagC | FlagD;
    

    it is the or of

    1000 |
    0010 |
    0001 =
    1011
    

    So in your example you are setting the unit flags to be Hour, Minute, Day and Month