一.定义
typedef enum{ //在这个地方,可以定义相同的名称,给要用到的类型起个标识符,这个地方,是可以省略的
unknown, //大括号里面的内容,依据程序员的需要来填充,使用逗号隔开,最后一个可以不使用符号,默认的序号是从0开始的,最好在标记时给它赋值=0
;如果在中途给它定义了数字,比如unknown=7,则以后的字符的序号依次递增,iPad=8
iPad,
iPhone
}TYPES; //在结尾时,使用分号来结束
enum相当于#define的用法,只是相对来说简单一些。使用了enum之后,在使用时,该类型的变量值只能在enum定义里面选取。
二.如何使用
我们最终的目的,是要把学习的内容在自己写代码的时候融入进去,那么在用的时候是怎么用的呢?我们就来一个小小的demo。
#include <stdio.h>
enum Devices{
iPhone = 0,
iPad,
iBall
};
int main(int argc, const char * argv[]) {
enum Devices dev;
switch (dev) {
case 0:
printf("这个是iPhone\n");
break;
case 1:
printf("这个是iPad\n");
break;
case 2:
printf("这个是iball");
break;
default:
break;
}
return 0;
}
输出内容是:
这个是iPhone
这样我们就可以减少代码的写入,将即将用到的变量全部都列举出来,然后用数字来代替。当然,上面的代码,是在Xcode下面的Application输出的。如果换位ios,道理也是一样的。
enum和enum typedef 在IOS中的使用
第一、typedef的使用
C语言里typedef的解释是用来声明新的类型名来代替已有的类型名,typedef为C语言的关键字,作用是为一种数据类型定义一个新名字。这里的数据类型包括内部数据类型(int,char等)和自定义的数据类型(struct等)
如:typedef char gender;
gender a;与char a;语句相同。
第二 、enum的使用
enum是枚举类型,
如:
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
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;