开发中经常遇到打印枚举的log,由于枚举是编译时候的,编译后并不会成为符号变量。
这是Stack Overflow上网友的回答:Enumerations in C are numbers that have convenient names inside your code. They are not strings, and the names assigned to them in the source code are not compiled into your program, and so they are not accessible at runtime.
枚举类型在C语言中是数字,为了方便插入代码。他们不会编译到程序中,所以,他们在运行时不能访问。
那么打印枚举中每一项的文本值可以这么做:(Objective-C语言)
定义一个Step的枚举,紧接着定义一个StepNames的指针数组,存放对应的文本string值。
typedef enum
{
Step_Initialization,/*初始化*/
Step_OffLine, /*离线*/
//Step_LogOut, /*注销*/
Step_GetNavi , /*导航*/
Step_Connecting, /*网络连接*/
Step_ConnectFailed,/*连接成功*/
Step_Connected, /*连接成功*/
Step_Logining, /*发送信令*/
Step_Logined, /*成功*/
Step_LoginFailed, /*失败*/
Step_BrokenLogined,/*断线重连*/
} Step;
//不要忘记补充下面的文字
__unused static const char *StepNames[] ={
"Step_Initialization",
"Step_OffLine",
//"Step_LogOut",
"Step_GetNavi",
"Step_Connecting",
"Step_ConnectFailed",
"Step_Connected",
"Step_Logining",
"Step_Logined",
"Step_LoginFailed",
"Step_BrokenLogined"
};
使用:其中Step是类中一个属性,这里因为业务需要重写了setter方法。当然,你也可以在其他地方使用下面代码。
//setter方法
-(void)setStep:(Step)step
{
int len = sizeof(StepNames);
if (step*4>len)
NSLOG(@"Step =[%d],请补充log",StepNames[step],step);//防止崩溃
else
NSLOG(@"Step =[%s%d]",StepNames[step],step);
}