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
};
- Gives a real, fixed-size type (here
NSInteger) - Compiler knows the type → better warnings, switch-statement checking
- Replaces the old “enum + separate typedef” pattern
NS_OPTIONS – for bitmasks
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
UIViewAutoresizingNone = 0,
UIViewAutoresizingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizingFlexibleWidth = 1 << 1,
UIViewAutoresizingFlexibleRightMargin = 1 << 2,
// …
};
- Same syntax as NS_ENUM, but tells the compiler values can be combined with
| - Enables bitwise operations with proper type safety
Rule of thumb
- Use NS_ENUM when only one value can be active (days of week, cell styles, etc.)
- Use NS_OPTIONS when multiple values can be combined (autoresizing masks, permissions, animation options, etc.)
Always prefer these macros over raw enum or old-style typedefs, they’re clearer, safer, and future-proof.
Category:
Tags:
Year: