位移枚举解析
2015-12-11 00:00
141 查看
位移枚举
位移枚举是非常古老的 C 语言技巧按位与如果都是 1 结果就是1
按位或如果都是 0 结果就是0
演练
定义枚举类型/// 操作类型枚举typedef enum { ActionTypeTop = 1 << 0, ActionTypeBottom = 1 << 1, ActionTypeLeft = 1 << 2, ActionTypeRight = 1 << 3} ActionType;
方法目标
根据操作类型参数,做出不同的响应
操作类型可以任意组合
方法实现
- (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];
代码小结
使用按位或可以给一个参数同时设置多个
类型
在具体执行时,使用
按位与可以判断具体的
类型
通过位移设置,就能够得到非常多的组合!
对于位移枚举类型,如果
传入 0,表示什么附加操作都不做,通常执行效率是最高的
如果开发中,看到位移的枚举,同时不要做任何的附加操作,参数可以直接输入 0!
iOS 特有语法
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);
}
}
相关文章推荐
- Microsoft.Aspnet.SingR2实例
- thread_ para
- linux 进程间通信 pipe
- linux 进程间通信 fifo
- linux 进程间通信 fifo_read
- linux 进程间通信fifo_write
- panic in gccgo
- discuz门户发布文章编辑名字用realname
- php开发工具 zend studio 12.5.1 中文版汉化
- 【嘉兴东臣php】HTML+CSS+JS基础学习周总结
- viewcontroller的跳转问题
- DB2 单ixf 恢复表数据
- python中通过main参数删除文件
- 怎样在iMindMap中添加分支
- 代理模式
- 最长LCS
- 线程间通信
- 在asp中,在子页面中如何让服务器控件的id不在运行后改变的方法
- 奇光影业招聘PHP工程师
- emoji表情