NS_ENUM & NS_OPTIONS

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容