美文网首页
NS_ENUM 和 NS_OPTIONS

NS_ENUM 和 NS_OPTIONS

作者: AprSnow | 来源:发表于2018-07-03 15:34 被阅读35次

Enumeration Macros

在Apple的《Adopting Modern Objective-C》一文中提到用 NS_ENUMNS_OPTIONS 代替C语言风格的enum
比如,
普通枚举

enum {
        UITableViewCellStyleDefault,
        UITableViewCellStyleValue1,
        UITableViewCellStyleValue2,
        UITableViewCellStyleSubtitle
};
typedef NSInteger UITableViewCellStyle;

最好写为:

typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
        UITableViewCellStyleDefault,
        UITableViewCellStyleValue1,
        UITableViewCellStyleValue2,
        UITableViewCellStyleSubtitle
};

位枚举

enum {
        UIViewAutoresizingNone                 = 0,
        UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,
        UIViewAutoresizingFlexibleWidth        = 1 << 1,
};
typedef NSUInteger UIViewAutoresizing;

最好写为:

typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
        UIViewAutoresizingNone                 = 0,
        UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,
        UIViewAutoresizingFlexibleWidth        = 1 << 1,
};

Difference

  • NS_ENUM 枚举项的值为 NSInteger,NS_OPTIONS 枚举项的值为 NSUInteger;
  • NS_ENUM 定义通用枚举,NS_OPTIONS 定义位移枚举

More

Adopting Modern Objective-C

相关文章

网友评论

      本文标题:NS_ENUM 和 NS_OPTIONS

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