Question

I would like to create a methods that takes a parameter "unitFlags" similar to Event Kit's

- (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)date.

In the previous method and the method shown below unitflags can be set to multiple values

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:date];

I see that these methods take a NSUInteger, but how do i determine the multiple values set once i unit flags in my methods custom implementation.

Was it helpful?

Solution 2

The key is in the definition of the enumerate values that can be passed (NSYearCalendarUnit):

typedef CF_OPTIONS(CFOptionFlags, CFCalendarUnit) {
kCFCalendarUnitEra = (1UL << 1),
kCFCalendarUnitYear = (1UL << 2),
kCFCalendarUnitMonth = (1UL << 3),
}

You need to define your own enumeration. Then, inside your class you can test the supplied value:

CFCalendarUnit testValue = ...;

if ((testValue & kCFCalendarUnitEra) == kCFCalendarUnitEra) {
    // it's an era
}
if ((testValue & kCFCalendarUnitYear) == kCFCalendarUnitYear) {
    // it's a year
}

OTHER TIPS

Since unitFlags is a bitmask, you can check it a specific flag is set like this:

if (unitFlags & NSYearCalendarUnit) { // notice it's & and not &&
    // The "year" flag is set
}
if (unitFlags & NSMonthCalendarUnit) {
    // The "month" flag is set
}

Use a bitmask for that, like:

UIViewAutoresizing

enum {
   UIViewAutoresizingNone                 = 0,
   UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,
   UIViewAutoresizingFlexibleWidth        = 1 << 1,
   UIViewAutoresizingFlexibleRightMargin  = 1 << 2,
   UIViewAutoresizingFlexibleTopMargin    = 1 << 3,
   UIViewAutoresizingFlexibleHeight       = 1 << 4,
   UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
typedef NSUInteger UIViewAutoresizing;

To check if the flag has the option you can use a method like:

- (BOOL)AutoresizingMask:(UIViewAutoresizing)autoresizing hasFlag:(UIViewAutoresizing)flag
{
    return (autoresizing & flag) != 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top