Objective-C 枚举、NS_ENUM 和 NS_OPTIONS

标签 objective-c cocoa enums

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

相关文章:

objective-c - CoreData主应用和后台进程,数据相同

python - 测试枚举列表中的成员身份失败

objective-c - 我在 info.plist 中的 NSAppTransportSecurity 设置不适用于所有定义的域和子域

objective-c - iPhone开发——可重用功能的最佳实践

objective-c - NSTableView 与窗口右侧对齐?

objective-c - 用未知数量的列填充 NSTableView

c++ - 未解析的外部符号 _declspec(dllimport)

java - 识别构造函数中的特定枚举

iphone - 为 IBOutletCollection 中的所有项目设置文本颜色

ios - 无法理解 Objective-C block 文档