iOS枚举类型宏定义

2016-08-19  本文已影响234人  chsasaw

NS_ENUMNS_OPTIONS提供了简洁的枚举类型变量的定义方法。这两个方法定义了枚举变量的数据类型和名称,并且告诉系统所占用的空间大小。在旧的编译器上能够被正常编译,在新的编译器上能定义基本数据类型。

NS_ENUM用来定义互斥的枚举值,如:

typedef NS_ENUM(NSInteger, UITableViewCellStyle) {

    UITableViewCellStyleDefault,

    UITableViewCellStyleValue1,

    UITableViewCellStyleValue2,

    UITableViewCellStyleSubtitle

};

NS_OPTIONS用来定义互相包含的位移操作相关的枚举值,如:

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;  

等效于上述定义。

上一篇 下一篇

猜你喜欢

热点阅读