1. NS_ENUM and NS_OPTIONS are perferred.
Introduced in Foundation with iOS 6 / OS X Mountain Lion, the NS_ENUM
and NS_OPTIONS macros are the new, preferred way to declare enum
types.
在OC中,推薦使用NS_ENUM 和 NS_OPTIONS來定義枚舉.
可以看到Apple公司自己就是使用這兩個宏來定義枚舉的.
2. 通用模式 - NS_ENUM
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) {
...
};
Refer from NSObjcRuntime.h
typedef NS_ENUM(NSInteger, EZLConnectionState)
{
EZLConnectionStateDisconnected = -1,
EZLConnectionStateConnected = 0,
EZLConnectionStateConnecting = 1
};
等價于:
enum EZLConnectionState : NSInteger
{
EZLConnectionStateDisconnected = -1,
EZLConnectionStateConnected = 0,
EZLConnectionStateConnecting = 1
};
typedef enum EZLConnectionState : NSInteger EZLConnectionState;
可以看出NS_ENUM實質是將C風格的enum定義和typedef合二為一.
3. 位操作模式 - NS_OPTIONS
typedef NS_OPTIONS(NSUInteger, UIControlState) {
UIControlStateNormal = 0,
UIControlStateHighlighted = 1 << 0, // used when UIControl isHighlighted is set
UIControlStateDisabled = 1 << 1,
UIControlStateSelected = 1 << 2, // flag usable by app (see below)
UIControlStateFocused NS_ENUM_AVAILABLE_IOS(9_0) = 1 << 3, // Applicable only when the screen supports focus
UIControlStateApplication = 0x00FF0000, // additional flags available for application use
UIControlStateReserved = 0xFF000000 // flags reserved for internal framework use
};
References:
http://nshipster.com/ns_enum-ns_options/
http://www.cnblogs.com/langtianya/p/3888924.html