位移枚举是很是古老的 C 语言技巧web
按位与
若是都是 1 结果就是1spa
按位或
若是都是 0 结果就是0code
定义枚举类型开发
/// 操做类型枚举typedef enum { ActionTypeTop = 1 << 0, ActionTypeBottom = 1 << 1, ActionTypeLeft = 1 << 2, ActionTypeRight = 1 << 3} ActionType;
方法目标it
根据操做类型参数,作出不一样的响应io
操做类型能够任意组合效率
方法实现sed
- (void)action:(ActionType)type { if (type == 0) { NSLog(@"无操做"); return; } if (type & ActionTypeTop) { NSLog(@"Top %tu", type & ActionTypeTop); } if (type & ActionTypeBottom) { NSLog(@"Bottom %tu", type & ActionTypeBottom); } if (type & ActionTypeLeft) { NSLog(@"Left %tu", type & ActionTypeLeft); } if (type & ActionTypeRight) { NSLog(@"Right %tu", type & ActionTypeRight); } }
方法调用技巧
ActionType type = ActionTypeTop | ActionTypeRight; [self action:type];
使用 按位或
能够给一个参数同时设置多个 类型
webkit
在具体执行时,使用 按位与
能够判断具体的 类型
经过位移设置,就可以获得很是多的组合!
对于位移枚举类型,若是传入 0
,表示什么附加操做都不作,一般执行效率是最高的
若是开发中,看到位移的枚举,同时不要作任何的附加操做,参数能够直接输入 0!
iOS 5.0以后,提供了新的枚举定义方式
定义枚举的同时,指定枚举中数据的类型
typedef NS_OPTIONS(NSUInteger, NSJSONReadingOptions)
位移枚举,能够使用 按位或
设置数值
typedef NS_ENUM(NSInteger, UITableViewStyle)
数字枚举,直接使用枚举设置数值
typedef NS_OPTIONS(NSUInteger, ActionType) {
ActionTypeTop = 1 << 0,
ActionTypeBottom = 1 << 1,
ActionTypeLeft = 1 << 2,
ActionTypeRight = 1 << 3
};
/*******位移枚举演练**********/
//按位与 同1为1 其余为0
//按位或 有1为1 其余为0
//typedef enum{
//
// ActionUp = 1 << 0,
// ActionDown = 1 << 1,
// ActionLeft = 1 << 2,
// ActionRight = 1 << 3,
//
//
//
//}ActionEnum;
//typedef NS_OPTIONS(NSInteger, Action){
//
// ActionUp = 1 << 0,
// ActionDown = 1 << 1,
// ActionLeft = 1 << 2,
// ActionRight = 1 << 3,
//
//
//
//} ;
//
typedef NS_ENUM(NSInteger,ActionEnum){
ActionUp = 1 << 0,
ActionDown = 1 << 1,
ActionLeft = 1 << 2,
ActionRight = 1 << 3,
};
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//按位或
[self didSelcted:ActionUp | ActionDown];
// 0 0 0 1
// 0 0 1 0
// 0 0 1 1 -- 3
}
- (void) didSelcted:(ActionEnum)action{
// action 0 0 1 1
// up 0 0 0 1
// 0 0 0 1 ---> 1
if ((action & ActionUp) == ActionUp) {
NSLog(@"ActionUp %ld",action);
}
// action 0 0 1 1
// up 0 0 1 0
// 0 0 1 0 ---> 2
if ((action & ActionDown) == ActionDown) {
NSLog(@" ActionDown%ld",action);
}
// action 0 0 1 1
// up 0 1 0 0
// 0 0 0 1 ---> 0
if ((action &ActionLeft ) == ActionLeft) {
NSLog(@"ActionLeft %ld",action);
}
// action 0 0 1 1
// up 1 0 0 0
// 0 0 0 0 ---> 0
if ((action & ActionRight) == ActionRight) {
NSLog(@"ActionRight %ld",action);
}
}