美文网首页常用类iOS开发
iOS枚举中的<<符号

iOS枚举中的<<符号

作者: 952625a28d0d | 来源:发表于2016-07-04 16:21 被阅读378次
  • 先来看一段代码
typedef enum{ 
   SDWebImageRetryFailed = 1 << 0,  
   SDWebImageLowPriority = 1 << 1,    
   SDWebImageCacheMemoryOnly = 1 << 2
} SDWebImageOptions;```

- 上面的<<符号是什么意思呢?

- 位操作法,即往左移动N位,举个例子,1的二进制表示是1,往左移一位就是10。这种枚举是一般叫做option。举个例子SDWebImageRetryFailed| SDWebImageLowPriority就是 01 | 10 即11 

enum UIViewAutoresizing {UIViewAutoresizingNone =0,
UIViewAutoresizingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizingFlexibleWidth = 1 << 1,
UIViewAutoresizingFlexibleRightMargin = 1 << 2,
UIViewAutoresizingFlexibleTopMargin = 1 << 3,
UIViewAutoresizingFlexibleHeight = 1 << 4,
UIViewAutoresizingFlexibleBottomMargin = 1 << 5,
}”```

Paste_Image.png
  • 由上图可以看出这样写的主要目的是为了用 | 写 有多个枚举值的枚举,其原理不过是位运算(二进制)相加的结果。由于二进制相加之后唯一,就确保了枚举的唯一性。

  • 手工去写位运算的需要花时间,好在Apple已经为我们准备的uint.所以,用下面这种方式来初始化一个位运算枚举。

typedef NS_ENUM(uint, Test)  
{  
    TestA,  
    TestB,  
    TestC,  
    TestD,  
    TestE    
};  ```

- 多枚举值 赋值方式如下:

Test tes = (TestA|TestB); ```

  • 判断枚举变量是否包含某个固定的枚举值,使用前需要确保枚举值以及各个组合的唯一性:
NSLog(@"%d %d %d %d %d",TestA,TestB,TestC,TestD,TestE);  
Test tes = (TestA|TestB);  
NSLog(@"%d",tes);  
NSLog(@"%d",(tes & TestA));  
  
if ((tes & TestA)) {  
    NSLog(@"有");  
}else  
{  
    NSLog(@"没有");  
}  
NSLog(@"%d",(tes & TestB));  
if ((tes & TestA)) {  
    NSLog(@"有");  
}else  
{  
    NSLog(@"没有");  
}  
  
NSLog(@"%d",(tes & TestC));  
if ((tes & TestC)) {  
    NSLog(@"有");  
}else  
{  
    NSLog(@"没有");  
}  ```

- 如果 没有包含,将返回0, 0表示false NO 则进入else

也可以随时为枚举变量累加某个值,但是要自己控制不要添加已经加入过的枚举值, 枚举变量的值不会有变动,但这样将会误导阅读代码的人

tes |=TestC; ```

有累加,自然有累减了,如果累减不存在的枚举值, 那么本次累减的枚举值,会自动累加上去.

tes^= TestE; 

相关文章

网友评论

  • dslCoding:你好这个enum中为什么要用位移操作,这样做有什么好处吗,请求帮助
    BoASir:组合使用的时候用,可以看看https://www.jianshu.com/p/97e582fe89f3

本文标题:iOS枚举中的<<符号

本文链接:https://www.haomeiwen.com/subject/ykacjttx.html