Search code examples
iphoneiosnscalendarnsdatecomponentsnsuinteger

NSCalendarUnit – modifying unitFlags


In my app I want to let user set display style of a date. I've considered to just modify unitFlags to achieve that. I mean this

NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSDayCalendarUnit;

But here's the question: How can I add or remove a NSCalendarUnit to this integer?

I'm using NSCalendar to get NSDateComponents from a date.

Sorry if the question is too stupid, I wasn't working enough with bitwise operations :(


Solution

  • I am not sure if this is what you are looking for, but you can add a flag using the "bitwise or" operator:

    unitFlags |= NSYearCalendarUnit;
    

    and remove a flag using "bitwise and" in combination with "bitwise complement";

    unitFlags &= ~NSYearCalendarUnit;
    

    To check for a flag:

    if ((unitFlags & NSYearCalendarUnit) != 0) {
        // NSYearCalendarUnit is set
    } else {
        // NSYearCalendarUnit is not set
    }