李洪強iOS開發之 - enum與typedef enum的用法
01 - 定義枚舉類型
上面我們就在ViewController.h定義了一個枚舉類型,枚舉類型的值默認是連續的自然數,例如例子中的
TO_BE_PAID=0,//開始
那么其后的就依次為1,2,3....所以一般只需要設置枚舉中第一個的值就可以。
注意: 在定義枚舉類型的時候一定要定義在.h中的#imort 和€interface之間定義,位置不能錯了
02 - 定義操作類型
enum和enum typedef 在IOS中的使用
第一、typedef的使用
C語言里typedef的解釋是用來聲明新的類型名來代替已有的類型名,typedef為C語言的關鍵字,作用是為一種數據類型定義一個新名字。這里的數據類型包括內部數據類型(int,char等)和自定義的數據類型(struct等)
如:typedef char gender;
gender a;與char a;語句相同。
第二 、enum的使用
enum是枚舉類型, enum用來定義一系列宏定義常量區別用,相當於一系列的#define xx xx,當然它后面的標識符也可當作一個類型標識符。
如:
enum AlertTableSections
{
kUIAction_Simple_Section = 1,
kUIAction_OKCancel_Section,
kUIAction_Custom_Section,
kUIAlert_Simple_Section,
kUIAlert_OKCancel_Section,
kUIAlert_Custom_Section,
};
kUIAction_OKCancel_Section的值為2.
第三、typedef enum 的使用
typedef enum則是用來定義一個數據類型,那么該類型的變量值只能在enum定義的范圍內取。
typedef enum {
UIButtonTypeCustom = 0, // no button type
UIButtonTypeRoundedRect, // rounded rect, flat white button, like in address card
UIButtonTypeDetailDisclosure,
UIButtonTypeInfoLight,
UIButtonTypeInfoDark,
UIButtonTypeContactAdd,
} UIButtonType;
UIButtonType表示一個類別,它的值只能是UIButtonTypeCustom....
在了解enum和typedef enum的區別之前先應該明白typedef的用法和意義。
C語言里typedef的解釋是用來聲明新的類型名來代替已有的類姓名,例如:
typedef int CHANGE;
指定了用CHANGE代表int類型,CHANGE代表int,那么:
int a,b;和CHANGE a,b;是等價的、一樣的。
方便了個人習慣,熟悉的人用CHANGE來定義int。
typedef為C語言的關鍵字,作用是為一種數據類型定義一個新名字。這里的數據類型包括內部數據類型(int,char等)和自定義的數據類型(struct等)。
而enum是枚舉類型,有了typedef的理解容易看出,typedef enum定義了枚舉類型,類型變量取值在enum{}范圍內取,在使用中二者無差別。
enum AlertTableSections
{
kUIAction_Simple_Section = 0,
kUIAction_OKCancel_Section,
kUIAction_Custom_Section,
kUIAlert_Simple_Section,
kUIAlert_OKCancel_Section,
kUIAlert_Custom_Section,
};
typedef enum {
UIButtonTypeCustom = 0, // no button type
UIButtonTypeRoundedRect, // rounded rect, flat white button, like in address card
UIButtonTypeDetailDisclosure,
UIButtonTypeInfoLight,
UIButtonTypeInfoDark,
UIButtonTypeContactAdd,
} UIButtonType;
看上面兩個例子更好理解,下面的是UIButton的API,UIButtonType指定的按鈕的類型,清楚名了,上面的直接調用enum里的元素就可以了。