user3741098
user3741098

Reputation:

Explication of one line in Objective-C Manual

I view the next line in the Apple manual and I don't understanding

NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;

The complete code is

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];

What does the | I know this charter for the OR operator !

In my logical unitFlags = NSMonthCalendarUnit OR NSDayCalendarUnit

Upvotes: 1

Views: 40

Answers (1)

Linuxios
Linuxios

Reputation: 35803

C and C-like/derived languages often use something called a bitfield to pass various combinations of flags to functions. Some integer is considered a bitfield, and each bit in the integer represents the boolean value of some flag. For example, if we had a 1 byte bitfield, it might look this:

10010101

That means that whatever flags are defined to be bit positions 0, 2, 4, 7 are set to true, and the others to false. Instead of making you construct this bitfield manually and remembering which bit is which flag, you usually construct it using bitwise operations and predefined constants.

In your case, NSMonthCalendarUnit is defined to be 01000, and NSDayCalendarUnit is defined to be 10000. When you bitwise OR (|) them together, you get 11000, the bitfield representing having both of those flags set.

Upvotes: 1

Related Questions