NS_ENUM & NS_OPTIONS

Introduced in Foundation with iOS 6 / OS X Mountain Lion, the NS_ENUM and NS_OPTIONS macros are the new, preferred way to declare enum types.

nshipster.com/ns_enum-ns_options/

NS_ENUM and NS_OPTIONS are the modern, Apple-approved way to declare enums and bit-masks.

NS_ENUM – for normal enumerated values

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

NS_OPTIONS – for bitmasks

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

Rule of thumb

Always prefer these macros over raw enum or old-style typedefs, they’re clearer, safer, and future-proof.


Category:

Year: