打印枚举中每一项的文本值

开发中经常遇到打印枚举的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);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值