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


#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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 阳春三月,来到北京。乍暖还寒,淡白而显得空洞的太阳一时还罩不住流动在空气中的寒冷。找到了应聘的诊所,规模...
    锦瑟无恙阅读 357评论 1 3
  • 《小王子》这本书是一个叫Antoine de Saint Exupéry的法国人写的,主要讲的是一个飞行员在飞机失...
    钤鱼摆摆阅读 225评论 1 1