iOS 枚舉類型 enum NS_ENUM NS_OPTIONS
一般情況下,我們採用C風格的enum關鍵字可以定義枚舉類型。
enum{
UIViewAnimationTransitionNone,
UIViewAnimationTransitionFlipFromLeft,
UIViewAnimationTransitionFlipFromRight,
UIViewAnimationTransitionCurlUp,
UIViewAnimationTransitionCurlDown,
} UIViewAnimationTransition;
//位移操作枚舉定義
enum {
UIViewAutoresizingNone = 0,
UIViewAutoresizingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizingFlexibleWidth = 1 << 1,
UIViewAutoresizingFlexibleRightMargin = 1 << 2,
UIViewAutoresizingFlexibleTopMargin = 1 << 3,
UIViewAutoresizingFlexibleHeight = 1 << 4,
UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
typedef NSUInteger UIViewAutoresizing;//使用NSUInteger的地方可以使用UIViewAutoresizing,//UIViewAutoresizing相當於NSUInteger的一個別名使用。
//因此一個UIViewAutoresizing的變數可以直接賦值給NSUInteger
枚舉值一般是4個位元組的int值,在64位系統上是8個位元組。
在iOS6和Mac OS 10.8以後Apple引入了兩個宏來重新定義這兩個枚舉類型,實際上是將enum定義和typedef合二為一,並且採用不同的宏來從代碼角度來區分。
NS_OPTIONS一般用來定義位移相關操作的枚舉值,我們可以參考UIKit.Framework的標頭檔,可以看到大量的枚舉定義。
typedef NS_ENUM(NSInteger, UIViewAnimationTransition) {
UIViewAnimationTransitionNone,//預設從0開始
UIViewAnimationTransitionFlipFromLeft,
UIViewAnimationTransitionFlipFromRight,
UIViewAnimationTransitionCurlUp,
UIViewAnimationTransitionCurlDown,
};
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
};
這兩個宏的定義在Foundation.framework的NSObjCRuntime.h中:
- #if (__cplusplus && __cplusplus >= 201103L && (__has_extension(cxx_strong_enums) || __has_feature(objc_fixed_enum))) || (!__cplusplus && __has_feature(objc_fixed_enum)) #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
- #if (__cplusplus) #define NS_OPTIONS(_type, _name) _type _name; enum : _type
- #else #define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type
- #endif #else
- #define NS_ENUM(_type, _name) _type _name; enum #define NS_OPTIONS(_type, _name) _type _name; enum
- #endif 將
typedef NS_ENUM(NSInteger, UIViewAnimationTransition) {
展開得到:
typedef enum UIViewAnimationTransition : NSInteger UIViewAnimationTransition;
enum UIViewAnimationTransition : NSInteger {
從枚舉定義來看,NS_ENUM和NS_OPTIONS本質是一樣的,僅僅從字面上來區分其用途。NS_ENUM是通用情況,NS_OPTIONS一般用來定義具有位移操作或特點的情況(bitmask)。
實際使用時,可以直接定義:
typedef enum : NSInteger {....} UIViewAnimationTransition;等效於上述定義。