枚舉類型 enum,NS_ENUM,NS_OPTIONS

  1. //位移操做枚舉定義  
  2. enum {  
  3.     UIViewAutoresizingNone                 = 0,  
  4.     UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,  
  5.     UIViewAutoresizingFlexibleWidth        = 1 << 1,  
  6.     UIViewAutoresizingFlexibleRightMargin  = 1 << 2,  
  7.     UIViewAutoresizingFlexibleTopMargin    = 1 << 3,  
  8.     UIViewAutoresizingFlexibleHeight       = 1 << 4,  
  9.     UIViewAutoresizingFlexibleBottomMargin = 1 << 5  
  10. };  
  11. typedef NSUInteger UIViewAutoresizing;//使用NSUInteger的地方能夠使用UIViewAutoresizing,//UIViewAutoresizing至關於NSUInteger的一個別名使用。  
  12. //所以一個UIViewAutoresizing的變量能夠直接賦值給NSUInteger  

枚舉值通常是4個字節的int值,在64位系統上是8個字節。 app

在iOS6和Mac OS 10.8之後Apple引入了兩個宏來從新定義這兩個枚舉類型,其實是將enum定義和typedef合二爲一,而且採用不一樣的宏來從代碼角度來區分。

NS_OPTIONS通常用來定義位移相關操做的枚舉值,咱們能夠參考UIKit.Framework的頭文件,能夠看到大量的枚舉定義。 url

  1. typedef NS_ENUM(NSInteger, UIViewAnimationTransition) {  
  2.     UIViewAnimationTransitionNone,//默認從0開始  
  3.     UIViewAnimationTransitionFlipFromLeft,  
  4.     UIViewAnimationTransitionFlipFromRight,  
  5.     UIViewAnimationTransitionCurlUp,  
  6.     UIViewAnimationTransitionCurlDown,  
  7. };  
  8.   
  9. typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {  
  10.     UIViewAutoresizingNone                 = 0,  
  11.     UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,  
  12.     UIViewAutoresizingFlexibleWidth        = 1 << 1,  
  13.     UIViewAutoresizingFlexibleRightMargin  = 1 << 2,  
  14.     UIViewAutoresizingFlexibleTopMargin    = 1 << 3,  
  15.     UIViewAutoresizingFlexibleHeight       = 1 << 4,  
  16.     UIViewAutoresizingFlexibleBottomMargin = 1 << 5  
  17. };  

這兩個宏的定義在Foundation.framework的NSObjCRuntime.h中: spa

  1. (__cplusplus && __cplusplus >= 201103L && (__has_extension(cxx_strong_enums) || __has_feature(objc_fixed_enum))) || (!__cplusplus && __has_feature(objc_fixed_enum))  
  2. #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type  
  3. #if (__cplusplus)  
  4. #define NS_OPTIONS(_type, _name) _type _name; enum : _type  
  5. #else  
  6. #define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type  
  7. #endif  
  8. #else  
  9. #define NS_ENUM(_type, _name) _type _name; enum  
  10. #define NS_OPTIONS(_type, _name) _type _name; enum  
  11. #endif  


  1. typedef NS_ENUM(NSInteger, UIViewAnimationTransition) {  
 展開獲得:
[cpp]  view plain copy
  1. typedef enum UIViewAnimationTransition : NSInteger UIViewAnimationTransition;  
  2. enum UIViewAnimationTransition : NSInteger {  

從枚舉定義來看,NS_ENUM和NS_OPTIONS本質是同樣的,僅僅從字面上來區分其用途。NS_ENUM是通用狀況,NS_OPTIONS通常用來定義具備位移操做或特色的狀況(bitmask)。 .net

實際使用時,能夠直接定義: blog

[cpp]  view plain copy
  1. typedef enum : NSInteger {....} UIViewAnimationTransition;  
等效於上述定義。

參考文檔: ip

1. http://nshipster.com/ns_enum-ns_options/ 文檔

2.http://iamthewalr.us/blog/2012/11/ns_enum-and-ns_options/ get

相關文章
相關標籤/搜索