编写高质量代码的52个有效方法

52个有效方法(5) - 用枚举表示状态、选项、状态码

2018-08-09  本文已影响8人  SkyMing一C

枚举(enum)

用 NS_ENUM 与 NS_OPTIONS 宏来定义枚举类型,并指明其底层数据类型。

/* NS_ENUM supports the use of one or two arguments. The first argument is always the integer type used for the values of the enum. The second argument is an optional type name for the macro. When specifying a type name, you must precede the macro with 'typedef' like so:
 
typedef NS_ENUM(NSInteger, NSComparisonResult) {
    ...
};
 
If you do not specify a type name, do not use 'typedef'. For example:
 
NS_ENUM(NSInteger) {
    ...
};
*/
#define NS_ENUM(...) CF_ENUM(__VA_ARGS__)
#define NS_OPTIONS(_type, _name) CF_OPTIONS(_type, _name)

枚举(Enum)与状态(states)

某个对象所经历的各种状态可以定义为一个的枚举集(enumeration set)

typedef NS_ENUM(NSInteger, UIViewAnimationTransition) {
    UIViewAnimationTransitionNone,
    UIViewAnimationTransitionFlipFromLeft,
    UIViewAnimationTransitionFlipFromRight,
    UIViewAnimationTransitionCurlUp,
    UIViewAnimationTransitionCurlDown,
};

枚举(enum)与选项(options)

在定义选项的时候,应该使用枚举类型。若这些选项可以彼此组合,则更应如此。只要枚举定义得对,各选项之间就可以通过 “按位或操作符”来组合。

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
};
UIViewAutoresizingNone                            0 0 0 0 0 0 0 0
UIViewAutoresizingFlexibleLeftMargin              0 0 0 0 0 0 0 1
UIViewAutoresizingFlexibleWidth                   0 0 0 0 0 0 1 0
UIViewAutoresizingFlexibleRightMargin             0 0 0 0 0 1 0 0
UIViewAutoresizingFlexibleTopMargin               0 0 0 0 1 0 0 0
UIViewAutoresizingFlexibleHeight                  0 0 0 1 0 0 0 0
UIViewAutoresizingFlexibleBottomMargin            0 0 1 0 0 0 0 0
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight 
                                                  0 0 0 1 0 0 1 0

枚举(enum)与状态码(codes)

枚举用法也可用于 switch 语句。在处理枚举类型的switch语句中不要实现default分支。

typedef NS_ENUM(NSUInteger, EOCConnectionState) {
    EOCConnectionStateDisconnected,
    EOCConnectionStateConnecting,
    EOCConnectionStateConnected
};

switch (_currentState) {
    EOCConnectionStateDisconnected:
      //...
      break;
    EOCConnectionStateConnecting:
      //...
      break;
    EOCConnectionStateConnected:
      //...
      break;
}
要点:
  1. 应该用枚举表示状态机的状态、传递给方法的选项以及状态码等值,给这些值起个易懂的名字,就像监听网络状态的枚举。

  2. 如果把传递给某个方法的选项表示为枚举类型,而多个选项又可同时使用,那么就将各选项定义为2的幂,以便通过按位或操作将其组合起来。

  3. 用 NS_ENUM 与 NS_OPTIONS 宏来定义枚举类型,并指明其底层数据类型。这样可以确保枚举是用开发者所选的底层数据类型实现出来的,而不会采用编译器所选的类型。

  4. 在处理枚举类型的switch语句中不要实现default分支。这样的话,加入新枚举之后,编译器就会提示开发者:switch语句并未处理所有枚举。

上一篇 下一篇

猜你喜欢

热点阅读