位移枚舉是很是古老的 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);
}
}