在Objective-C中可以通过三种方式来定义一个枚举类型。
一、C语言中的枚举
C语言中的枚举形如:
enum EOCConnectionState{
EOCConnectionStateDisconnected,
EOCConnectionStateConnecting,
EOCConnectionStateConnected
};
//或者
typedef enum EOCConnectionState{
EOCConnectionStateDisconnected,
EOCConnectionStateConnecting,
EOCConnectionStateConnected
}EOCConnectionState;
二、C++11新特性枚举
C++11标准中修订了枚举的某些特性,其中一项改动是:可以指明用何种“底层数据类型”来保存枚举变量,形如:
enum EOCConnectionState : NSInteger {
EOCConnectionStateDisconnected,
EOCConnectionStateConnecting,
EOCConnectionStateConnected
};
上述代码的意思,以NSInteger类型来保存EOCConnectionState变量。
好处:从此可以前向声明指定枚举类型了。
三、OC的骚操作:NS_ENUM宏
在Foundation框架中,定义了一个辅助的宏用来定义枚举类型,形如:
typedef NS_ENUM(NSInteger,EOCConnectionState){
EOCConnectionStateDisconnected,
EOCConnectionStateConnecting,
EOCConnectionStateConnected
};
这个宏的作用是,如果编译器支持C++11新标准,那么就使用新语法,否则就使用旧式语法。
本文内容来自——《Effective Objective-C 2.0》第5条:用枚举表示状态、选项、状态码
网友评论