位移枚举

使用场景:同一次操作有多个选项,可以同时多选同时禁用
摘取一段定义好的iOS代码


typedef NS_OPTIONS(NSUInteger, NSKeyValueObservingOptions) {
    NSKeyValueObservingOptionNew =0x01,    // = 1 << 0    , 1
    NSKeyValueObservingOptionOld =0x02,    // = 1 << 1     , 2
    NSKeyValueObservingOptionInitial NS_ENUM_AVAILABLE(10_5,2_0) =0x04,     // = 1 << 2    , 4
    NSKeyValueObservingOptionPrior NS_ENUM_AVAILABLE(10_5,2_0) =0x08    // = 1 << 3    , 8
};

写一个方法,需要选择两种特性来实现


- (void)chooseTwoCharacter:(NSKeyValueObservingOptions)options {
    if (options == 0) {
        return;
    }
    else if (options & NSKeyValueObservingOptionNew == 
NSKeyValueObservingOptionNew) {
        NSLog(@"choose NSKeyValueObservingOptionNew");
    }
    else if (options & NSKeyValueObservingOptionNew == 
NSKeyValueObservingOptionOld) {
        NSLog(@"choose NSKeyValueObservingOptionOld");
    }
    else if (options & NSKeyValueObservingOptionNew == 
NSKeyValueObservingOptionInitial) {
        NSLog(@"choose NSKeyValueObservingOptionInitial");
    }
    else if (options & NSKeyValueObservingOptionNew == 
NSKeyValueObservingOptionPrior) {
        NSLog(@"choose NSKeyValueObservingOptionPrior");
     }
}

那么我们在调用的时候可以将需要选择的枚举值按位或,或者按十进制相加


NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld; // 0x0011
[self chooseTwoCharacter:options];
NSKeyValueObservingOptions options2 = NSKeyValueObservingOptionNew + NSKeyValueObservingOptionOld; // 3
[self chooseTwoCharacter:options2];

你可能感兴趣的:(位移枚举)