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

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

枚举是一种常量命名方式,某个对象所经历的各种状态就可以定义为一个简单的枚举集(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
};

其二进制值如图所示:


第 5 条:用枚举表示状态、选项、状态码_第1张图片
二进制值示意图
  • 此外,枚举用法也可用于 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 条:用枚举表示状态、选项、状态码)