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
};