OC中的枚举
- 方法一
typedef enum{
TestA = 0;
TestB,
TestC,
TestD
}Test;//枚举名称
- 方法二
typedef NS_ENUM (NSInteger, Test){
TestA = 0,
TestB = 1,
TestC = 2,
TestD = 3
};//结构比较清晰(推荐)
- 方法三
typedef NS_ENUM(NSInteger, Test)
{
TestA = 1, //1 1 1
TestB = 1 << 1, //2 2 10 转换成10进制 2
TestC = 1 << 2, //4 3 100 转换成10进制 4
TestD = 1 << 3, //8 4 1000 转换成10进制 8
TestE = 1 << 4 //16 5 10000 转换成10进制 16
}
/*
*当一个枚举变量可能要代表多个枚举值的时候,其实给一个枚举变量赋予多
*个枚举值的时候,原理知识把各个枚举值加起来罢了,当加起来以后,就获
*得了一个新的值,那么为了保证这个值的唯一性,这时候就体现了位运算的
*重要作用。
*位运算可以保证枚举值组合的唯一性
*因为位运算的计算方式是将二进制转换成十进制,也就是说,枚举值里面存
*取的是计算后的十进制值
*打个比方,通过上面的位运算方式设定好枚举,打印出来的枚举值分别是:
*1 2 4 8 16
*这5个数字,无论你如何组合在一起,也不会产生两个同样的数字
*/
- 方法四
/*手工去创建位运算枚举,还要稍微有点花时间的,Apple已经为我们准备的* uint,所以,可以用下面这种方式来初始化一个位运算枚举。*/
typedef NS_ENUM (uint, Test){
TestA,
TestB,
TestC,
TestD
};
- 方法五
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
ZLAutoresizingNone = 0,
ZLAutoresizingFlexibleLeftMargin = 1 << 0,
ZLAutoresizingFlexibleWidth = 1 << 1,
ZLAutoresizingFlexibleRightMargin = 1 << 2,
ZLAutoresizingFlexibleTopMargin = 1 << 3,
ZLAutoresizingFlexibleHeight = 1 << 4,
ZLAutoresizingFlexibleBottomMargin = 1 << 5
};
多枚举值 赋值方式如下:
Test test = (TestA|TestB);
Tips:
枚举值一般是4字节的Int值,在64位系统上是8个字节
在iOS6和Mac OS 10.8以后Apple引入了两个宏来重新定义这两个枚举类型,实际上是将enum定义和typedef合二为一,并且采用不容的宏来从代码角度来区分。
NS_OPTIONS一般用来定义位移相关的操作的枚举值,我们可以参考UIKit.Framework的头文件,可以看到大量的枚举定义。比如:
typedef NS_ENUM(NSInteger, UIViewAnimationTransition) {
UIViewAnimationTransitionNone,//默认从0开始
UIViewAnimationTransitionFlipFromLeft,
UIViewAnimationTransitionFlipFromRight,
UIViewAnimationTransitionCurlUp,
UIViewAnimationTransitionCurlDown,
};
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
UIViewAutoresizingNone = 0,
UIViewAutoresizingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizingFlexibleWidth = 1 << 1,
UIViewAutoresizingFlexibleRightMargin = 1 << 2,
UIViewAutoresizingFlexibleTopMargin = 1 << 3,
UIViewAutoresizingFlexibleHeight = 1 << 4,
UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};