20170317 NS_OPTIONS

详解枚举NS_OPTIONS与NS_ENUM的区别与格式

typedef NS_OPTIONS(NSUInteger, UISwipeGestureRecognizerDirection) {
    UISwipeGestureRecognizerDirectionNone = 0,  //值为0
    UISwipeGestureRecognizerDirectionRight = 1 << 0,  //值为2的0次方
    UISwipeGestureRecognizerDirectionLeft = 1 << 1,  //值为2的1次方
    UISwipeGestureRecognizerDirectionUp = 1 << 2,  //值为2的2次方
    UISwipeGestureRecognizerDirectionDown = 1 << 3  //值为2的3次方
};

小括号中第一个为NSUInteger这个为固定值,第二个为枚举类型,自己定义,大括号中枚举项必须全部包含小括号的枚举类型,枚举项后面再跟上几个值的区别,这里枚举项是NSUInteger类型,它的值我已经标记了,看上面注释,当然也可以像下方这样写枚举,但是官方推荐格式为上面那种。





Enum-枚举的正确使用-Effective-Objective-C-读书笔记-Item-5

这里的选项是用位运算的方式定义的,这样的好处就是,我们的选项变量可以如下表示:

//用“或”运算同时赋值多个选项
TTGDirection direction = TTGDirectionTop | TTGDirectionLeft | TTGDirectionBottom;
//用“与”运算取出对应位
if (direction & TTGDirectionTop) {
    NSLog(@"top");
}
if (direction & TTGDirectionLeft) {
    NSLog(@"left");
}
if (direction & TTGDirectionRight) {
    NSLog(@"right");
}
if (direction & TTGDirectionBottom) {
    NSLog(@"bottom");
}

direction变量的实际内存如下:

20170317 NS_OPTIONS_第1张图片
blog_effective_objective_c_5_enum_2.jpg

你可能感兴趣的:(20170317 NS_OPTIONS)