美文网首页
枚举类型 enum,NS_ENUM,NS_OPTIONS

枚举类型 enum,NS_ENUM,NS_OPTIONS

作者: ganser | 来源:发表于2016-08-13 22:35 被阅读353次

    c中定义的枚举类型enum,一般是4个字节的int值,在64位系统上是8个字节。

    enum enum_type_name
    {
        ENUM_CONST_1,
        ENUM_CONST_2,
        ENUM_CONST_n
    } enum_variable_name;
    
    - (void)test {
        enum_variable_name = 1;
        enum enum_type_name aa = 2;
        NSInteger aww = ENUM_CONST_1;
    }
    

    在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 {
    

    参考文档
    http://blog.csdn.net/annkie/article/details/9877643

    相关文章

      网友评论

          本文标题:枚举类型 enum,NS_ENUM,NS_OPTIONS

          本文链接:https://www.haomeiwen.com/subject/zgkysttx.html