I’m reading Apple’s documentation on NSDate. In one of their code examples I see something I haven’t seen before:
doc link. Here’s the example code.
NSDate *startDate = ...;
NSDate *endDate = ...;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:startDate
toDate:endDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];
I’m really confused by the use of the (OR) | operator when assigning value(s) to unitFlags. Can someone tell me what’s happening there? Do they both get assigned or does it check on first, and if nil looks for the other? Thank you in advance.
That’s not the OR operator (||). That’s the bitwise-OR operator, and may be the problem with your understanding.
If you have a look at the definition for the enums you used, you’ll see they are defined for compatibility and the base enum is
CFCalendarUnit.So let’s have a look at a snippet the definition for
CFCalendarUnitHave a look at the values that the enums have been assigned to:
Notice that each of the results in binary has only one (1) in it.
Using the bitwise-OR operator:
“Bitwise” means take each bit and perform the operation, in this case OR
You then pass this value to your calendar, where it will decode the information using a command like the following:
Using this technique. You can store 32 boolean pieces of information in a single 32-bit int by “flagging” each of the bits and quickly compound and retrieve information. This avoids methods like: