使用unitFlags创建自定义方法

时间:2013-05-10 21:59:38

标签: ios objective-c nsuinteger

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

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

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

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

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

3 个答案:

答案 0 :(得分:2)

由于unitFlags是一个位掩码,你可以检查一个特定的标志是这样设置的:

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

答案 1 :(得分:1)

使用位掩码,例如:

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;

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

- (BOOL)AutoresizingMask:(UIViewAutoresizing)autoresizing hasFlag:(UIViewAutoresizing)flag
{
    return (autoresizing & flag) != 0;
}

答案 2 :(得分: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
}