ns_options ns_enum區別

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

typedef NS_ENUM(NSInteger, UIViewAnimationTransition) {  spa

    UIViewAnimationTransitionNone,//默認從0開始  .net

    UIViewAnimationTransitionFlipFromLeft,  orm

    UIViewAnimationTransitionFlipFromRight,  blog

    UIViewAnimationTransitionCurlUp,  ip

    UIViewAnimationTransitionCurlDown,  文檔

    };  it

  1.   

  2. typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {  io

  3.     UIViewAutoresizingNone                 = 0,  im

  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. };  

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

  1. #if (__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) {  

 展開獲得:

  1. typedef enum UIViewAnimationTransition : NSInteger UIViewAnimationTransition;  

  2. enum UIViewAnimationTransition : NSInteger {  

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

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

  1. typedef enum : NSInteger {....} UIViewAnimationTransition;  

等效於上述定義。

參考文檔:

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

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

原文:http://blog.csdn.net/annkie/article/details/9877643

相關文章
相關標籤/搜索