在 Objective-C 中创建具有特定类型的枚举的正确方法是什么? NS_ENUM 和 NS_OPTIONS 是如何工作的? NS_OPTIONS 用于 mask ,例如 NSAutoresizing?谢谢。
Code from NSObjCRuntime.h
#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
#define NS_OPTIONS(_type, _name) _type _name; enum : _type
最佳答案
示例来自 NSHipster . NS_OPTIONS 以类似的方式使用,但对于通常是位掩码的枚举
代替
typedef enum {
UITableViewCellStyleDefault,
UITableViewCellStyleValue1,
UITableViewCellStyleValue2,
UITableViewCellStyleSubtitle
} UITableViewCellStyle;
或
typedef enum {
UITableViewCellStyleDefault,
UITableViewCellStyleValue1,
UITableViewCellStyleValue2,
UITableViewCellStyleSubtitle
};
typedef NSInteger UITableViewCellStyle;
这样做:
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
};
关于Objective-C 枚举、NS_ENUM 和 NS_OPTIONS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14080750/