iOS-行知程序员

简单小demo,了解OC中"位移枚举"的本质

2016-04-15  本文已影响248人  hcr123yeah

#import "ViewController.h"
typedef NS_OPTIONS(NSUInteger, kActionType) {
    kActionTypeTop    =    1 << 0, // 1
    kActionTypeBottom =    1 << 1, // 2
    kActionTypeLeft   =    1 << 2, // 4
    kActionTypeRight  =    1 << 3, // 8
};

@interface ViewController ()

@end

@implementation ViewController

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{

    [self demo:kActionTypeBottom | kActionTypeRight];
    NSLog(@"++++++++++");
    [self demo:kActionTypeTop | kActionTypeLeft | kActionTypeRight];
}

// 位移枚举在传入参数时,是使用 或运算 的方式,
/*
// 比如传进来的值是 10,也就是 1010 ;
//1010;
//0010;
 让 10 与上 2 得 2
 让 10 与上 8 得 8
 所以只要二进制位上有值, 就能获得对应的值
 
 */
//传多个参数 3个
//| (或运算符)   0|1 = 1 0|0 = 0 1|1 = 1  只要有1那么结果就是1
//& (与运算符)   0&1 = 0 0&0 = 0 1&1 = 1  只要有0那么结果就是0
-(void)demo:(kActionType)type
{
    NSLog(@"%zd",type);
    
    if (type & kActionTypeTop) {
        NSLog(@"向上---%zd",type & kActionTypeTop);
    }
//    1010;
//    0010;
    
    if (type & kActionTypeBottom) {
        NSLog(@"向下---%zd",type & kActionTypeBottom);
    }
    
    if (type & kActionTypeRight) {
        NSLog(@"向右---%zd",type & kActionTypeRight);
    }
    
    if (type & kActionTypeLeft) {
        NSLog(@"向左---%zd",type & kActionTypeLeft);
    }
    
    
}

/*
 控制台输出:
10
向下---2
向右---8
 
++++++++++
 
13
向上---1
向右---8
向左---4
 */
@end
上一篇 下一篇

猜你喜欢

热点阅读