0

我有相反的问题

如果我有:

typedef enum {
    SUNDAY = (1 << 0),
    MONDAY = (1 << 1),
    TUESDAY = (1 << 2),
    WEDNESDAY = (1 << 3),
    THURSDAY = (1 << 4),
    FRIDAY = (1 << 5),
    SATURDAY = (1 << 6),
} PFDateDays;

我的输入是65例如(SUNDAY,SATURDAY)有一种聪明的方法可以从枚举中提取这些值?

这是我的方法:

-(NSMutableArray*)selectFromMyEnum {
    NSMutableArray *returnArray = [[NSMutableArray alloc] init];
    int myInput = 62;
    NSArray *enumArray = @[@(SATURDAY),@(FRIDAY),@(THURSDAY),@(WEDNESDAY),@(TUESDAY),@(MONDAY),@(SUNDAY)];
    for(NSNumber *numberInEnumArray in enumArray) {
        if(myInput >= [numberInEnumArray integerValue]) {
            [returnArray addObject:numberInEnumArray];
            myInput -= [numberInEnumArray integerValue];
        }
    }
    NSLog(@"%@",returnArray);
    return returnArray;
}

这是输出:

(
    64, //SATURDAY
    1 //SUNDAY
)

所以这是正确的。但也许有一种我不知道的方法允许我在没有这个毫无意义的分配枚举到数组等的情况下做到这一点。

4

1 回答 1

3

好吧,我首先想到的就是这个。由于您的枚举很好地用于标记,您可以执行以下操作:

从您的最高枚举值 (SATURDAY) 开始,并使用按位和 ( &) 检查您的值是否包含它。然后将比较值右移 1 并重复,直到比较值为零。

PFDateDays comparison = SATURDAY;

//If your enum doesn't end at 1 like the above example,
//you could also use >= SUNDAY
while(((int)comparison) > 0) {
    if((myVal & comparison) == comparison)
        //Do what you want, this value is valid

    comparison = comparison >> 1;
}
于 2013-08-05T09:18:27.070 回答