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

2016-01-06  本文已影响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;
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
};

其二进制值如图所示:


二进制值示意图
typedef NS_ENUM(NSUInteger, EOCConnectionState) {
    EOCConnectionStateDisconnected,
    EOCConnectionStateConnecting,
    EOCConnectionStateConnected
};

switch (_currentState) {
    EOCConnectionStateDisconnected:
      //...
      break;
    EOCConnectionStateConnecting:
      //...
      break;
    EOCConnectionStateConnected:
      //...
      break;
}

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

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

上一篇下一篇

猜你喜欢

热点阅读