第 5 條:用枚舉表示狀態(tài)、選項(xiàng)、狀態(tài)碼

在用一系列常量來表示錯(cuò)誤狀態(tài)碼或可組合的選項(xiàng)時(shí),很適合 枚舉 為其命名。

枚舉是一種常量命名方式,某個(gè)對(duì)象所經(jīng)歷的各種狀態(tài)就可以定義為一個(gè)簡(jiǎn)單的枚舉集(enumeration set)。例如:

enum EOCConnectionState {
     EOCConnectionStateDisconnected,
     EOCConnectionStateConnecting,
     EOCConnectionStateConnected,
};

編譯器會(huì)為每個(gè)枚舉值分配一個(gè)獨(dú)有的編號(hào),從0開始,依次加1。一個(gè)字節(jié)最多可表示0~255共256種(2^8)枚舉變量。

定義枚舉變量:

enum EOCConnectionState state = EOCConnectionStateDisconnected;

為簡(jiǎn)便起見,可以使用 typedef 關(guān)鍵字重新定義枚舉類型:

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

現(xiàn)在就可以不寫 enum,直接定義了:

EOCConnectionState state = EOCConnectionStateDisconnected;
  • 指定“底層數(shù)據(jù)類型”(underlying type)(C++11標(biāo)準(zhǔn))的語法:
enum EOCConnectionState : NSInteger {
    /*...*/ 
}
  • 指定分配的序號(hào):
enum EOCConnectionState {
    EOCConnectionStateDisconnected = 1,
    EOCConnectionStateConnecting, //接下來的值會(huì)依次遞增1
    EOCConnectionStateConnected
};
  • 若定義的枚舉選項(xiàng)可以彼此組合,則更應(yīng)如此。例如:
// 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
};

其二進(jìn)制值如圖所示:


二進(jìn)制值示意圖
  • 此外,枚舉用法也可用于 switch 語句中,例如:
typedef NS_ENUM(NSUInteger, EOCConnectionState) {
    EOCConnectionStateDisconnected,
    EOCConnectionStateConnecting,
    EOCConnectionStateConnected
};

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

注:若用枚舉來定義狀態(tài)機(jī)(state machine),最好不要有 default 分支。

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容