Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NS_ENUM vs enum

Tags:

objective-c

Objective C provides several ways to declare an enumeration. It could be declared via typedef enum or NS_ENUM. NS_ENUM macro takes type name as a parameter, and I do not completely understand its meaning. I didn't find description of NS_ENUM macro in official Apple documentation. What's a difference between using enum and NS_ENUM? And an other question if it's possible to use any other type in NS_ENUM instead NSInteger and its relative integer types?

like image 448
Rostyslav Druzhchenko Avatar asked May 01 '14 10:05

Rostyslav Druzhchenko


People also ask

What is the difference between creating enum using Ns_enum and using typedef enum?

First, NS_ENUM uses a new feature of the C language where you can specify the underlying type for an enum. In this case, the underlying type for the enum is NSInteger (in plain C it would be whatever the compiler decides, char, short, or even a 24 bit integer if the compiler feels like it).

How do I create an enum in Objective C?

Objective-C Language Enums Defining an enumtypedef NS_ENUM(NSUInteger, MyEnum) { MyEnumValueA = 0, MyEnumValueB = 5, MyEnumValueC = 10, }; You can also specify on the first value and all the following will use it with increment: typedef NS_ENUM(NSUInteger, MyEnum) { MyEnumValueA = 0, MyEnumValueB, MyEnumValueC, };


1 Answers

NSHipster provided a very nice post that explains this thoroughly:

http://nshipster.com/ns_enum-ns_options/

To quote the bottom line:

This approach combines the best of all of the aforementioned approaches (enum, typedef enum), and even provides hints to the compiler for type-checking and switch statement completeness.

like image 77
Stavash Avatar answered Oct 27 '22 23:10

Stavash