枚舉類型的定義
enum 標(biāo)示符{
枚舉數(shù)據(jù)表
}套啤;
枚舉數(shù)據(jù)(枚舉常量)是一些特定的標(biāo)識(shí)符彤侍,標(biāo)識(shí)符代表什么含義肠缨,完全由程序員決定。數(shù)據(jù)枚舉的順序規(guī)定了枚舉數(shù)據(jù)的序號(hào)盏阶,從0開(kāi)始晒奕,依次遞增。
例如:
enum status{
OK,
NO,
}
enum 和enum typedef 的使用
c語(yǔ)言里typedef的解釋是用來(lái)聲明新的類型名來(lái)代替已有的類型名名斟,typedef為C語(yǔ)言的關(guān)鍵字脑慧,作用是為一種數(shù)據(jù)類型定義一個(gè)新名字。這里的數(shù)據(jù)類型包括內(nèi)部數(shù)據(jù)類型(int,char等)和自定義的數(shù)據(jù)類型(struct等)砰盐。
enum是枚舉類型闷袒, enum用來(lái)定義一系列宏定義常量區(qū)別用,相當(dāng)于一系列的#define xx xx岩梳,當(dāng)然它后面的標(biāo)識(shí)符也可當(dāng)作一個(gè)類型標(biāo)識(shí)符囊骤。
enum AlertStatus{
AlertStatus_simple = 1,
AlertStatus_Custom,
AlertStatus_sure冀值,
AlertStatus_cancel也物,
};
typedef enum {
UIButtonTypeCustom = 0,
UIButtonTypeRoundedRect,
UIButtonTypeDetailDisclosure,
UIButtonTypeInfoLight,
UIButtonTypeInfoDark,
UIButtonTypeContactAdd,
}UIButtonType;
enum與狀態(tài)(states)
typedef enum _TTGState {
TTGStateOK = 0,
TTGStateError,
TTGStateUnknow
} TTGState;
//指明枚舉類型
TTGState state = TTGStateOK;
//使用
- (void)dealWithState:(TTGState)state {
switch (state) {
case TTGStateOK: //...
break;
case TTGStateError: //...
break;
case TTGStateUnknow: //...
break;
}
}
enum與選項(xiàng) (options)
//方向池摧,可同時(shí)支持一個(gè)或多個(gè)方向
typedef enum _TTGDirection {
TTGDirectionNone = 0,
TTGDirectionTop = 1 << 0,
TTGDirectionLeft = 1 << 1,
TTGDirectionRight = 1 << 2,
TTGDirectionBottom = 1 << 3
} TTGDirection;
//使用
//用“或”運(yùn)算同時(shí)賦值多個(gè)選項(xiàng)
TTGDirection direction = TTGDirectionTop | TTGDirectionLeft | TTGDirectionBottom;
//用“與”運(yùn)算取出對(duì)應(yīng)位
if (direction & TTGDirectionTop) {
NSLog(@"top");
}
if (direction & TTGDirectionLeft) {
NSLog(@"left");
}
if (direction & TTGDirectionRight) {
NSLog(@"right");
}
if (direction & TTGDirectionBottom) {
NSLog(@"bottom");
}
在開(kāi)發(fā)過(guò)程中焦除,最好所有的枚舉都用“NS_ENUM”和“NS_OPTIONS”定義激况,保證統(tǒng)一作彤。
//NS_ENUM,定義狀態(tài)等普通枚舉
typedef NS_ENUM(NSUInteger, TTGState) {
TTGStateOK = 0,
TTGStateError,
TTGStateUnknow
};
//NS_OPTIONS乌逐,定義選項(xiàng)
typedef NS_OPTIONS(NSUInteger, TTGDirection) {
TTGDirectionNone = 0,
TTGDirectionTop = 1 << 0,
TTGDirectionLeft = 1 << 1,
TTGDirectionRight = 1 << 2,
TTGDirectionBottom = 1 << 3
};