0

我想创建一个采用类似于 Event Kit 的参数“unitFlags”的方法

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

在前面的方法和下面显示的方法中,unitflags 可以设置为多个值

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

我看到这些方法采用 a NSUInteger,但是我如何确定在我的方法自定义实现中设置单位标志后设置的多个值。

4

3 回答 3

2

由于unitFlags是位掩码,因此您可以检查它是否设置了特定标志,如下所示:

if (unitFlags & NSYearCalendarUnit) { // notice it's & and not &&
    // The "year" flag is set
}
if (unitFlags & NSMonthCalendarUnit) {
    // The "month" flag is set
}
于 2013-05-10T22:03:03.103 回答
1

为此使用位掩码,例如:

UIView自动调整大小

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

要检查标志是否有选项,您可以使用如下方法:

- (BOOL)AutoresizingMask:(UIViewAutoresizing)autoresizing hasFlag:(UIViewAutoresizing)flag
{
    return (autoresizing & flag) != 0;
}
于 2013-05-10T22:02:05.633 回答
1

关键在于可以传递的枚举值的定义(NSYearCalendarUnit):

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

您需要定义自己的枚举。然后,在您的类中,您可以测试提供的值:

CFCalendarUnit testValue = ...;

if ((testValue & kCFCalendarUnitEra) == kCFCalendarUnitEra) {
    // it's an era
}
if ((testValue & kCFCalendarUnitYear) == kCFCalendarUnitYear) {
    // it's a year
}
于 2013-05-10T22:05:15.547 回答