美文网首页
第 5 条:用枚举表示状态、选项、状态码

第 5 条:用枚举表示状态、选项、状态码

作者: 对歌当酒 | 来源:发表于2016-01-06 21:34 被阅读128次

    在用一系列常量来表示错误状态码或可组合的选项时,很适合 枚举 为其命名。

    枚举是一种常量命名方式,某个对象所经历的各种状态就可以定义为一个简单的枚举集(enumeration set)。例如:

    enum EOCConnectionState {
         EOCConnectionStateDisconnected,
         EOCConnectionStateConnecting,
         EOCConnectionStateConnected,
    };
    

    编译器会为每个枚举值分配一个独有的编号,从0开始,依次加1。一个字节最多可表示0~255共256种(2^8)枚举变量。

    定义枚举变量:

    enum EOCConnectionState state = EOCConnectionStateDisconnected;
    

    为简便起见,可以使用 typedef 关键字重新定义枚举类型:

    enum EOCConnectionState {
         EOCConnectionStateDisconnected,
         EOCConnectionStateConnecting,
         EOCConnectionStateConnected,
    };
    typedef enum EOCConnectionState EOCConnectionState;
    

    现在就可以不写 enum,直接定义了:

    EOCConnectionState state = EOCConnectionStateDisconnected;
    
    • 指定“底层数据类型”(underlying type)(C++11标准)的语法:
    enum EOCConnectionState : NSInteger {
        /*...*/ 
    }
    
    • 指定分配的序号:
    enum EOCConnectionState {
        EOCConnectionStateDisconnected = 1,
        EOCConnectionStateConnecting, //接下来的值会依次递增1
        EOCConnectionStateConnected
    };
    
    • 若定义的枚举选项可以彼此组合,则更应如此。例如:
    // UIView.h
    typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
        UIViewAutoresizingNone                 = 0,
        UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,
        UIViewAutoresizingFlexibleWidth        = 1 << 1,
        UIViewAutoresizingFlexibleRightMargin  = 1 << 2,
        UIViewAutoresizingFlexibleTopMargin    = 1 << 3,
        UIViewAutoresizingFlexibleHeight       = 1 << 4,
        UIViewAutoresizingFlexibleBottomMargin = 1 << 5
    };
    

    其二进制值如图所示:


    二进制值示意图
    • 此外,枚举用法也可用于 switch 语句中,例如:
    typedef NS_ENUM(NSUInteger, EOCConnectionState) {
        EOCConnectionStateDisconnected,
        EOCConnectionStateConnecting,
        EOCConnectionStateConnected
    };
    
    switch (_currentState) {
        EOCConnectionStateDisconnected:
          //...
          break;
        EOCConnectionStateConnecting:
          //...
          break;
        EOCConnectionStateConnected:
          //...
          break;
    }
    

    注:若用枚举来定义状态机(state machine),最好不要有 default 分支。

    主要来源:《Effective Objective-C 2.0》

    相关文章

      网友评论

          本文标题:第 5 条:用枚举表示状态、选项、状态码

          本文链接:https://www.haomeiwen.com/subject/lfrzhttx.html