简体   繁体   中英

NS_ENUM vs enum

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?

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 .

主要区别在于typedef NS_ENUM正确转换为Swift枚举,而typedef enum则不能。

Here is the link to the official Apple's documentation:
https://developer.apple.com/library/content/releasenotes/ObjectiveC/ModernizationObjC/AdoptingModernObjective-C/AdoptingModernObjective-C.html#//apple_ref/doc/uid/TP40014150-CH1-SW6

From the subsection titled "Enumeration Macros":

The NS_ENUM and NS_OPTIONS macros provide a concise, simple way of defining enumerations and options in C-based languages. These macros improve code completion in Xcode and explicitly specify the type and size of your enumerations and options. Additionally, this syntax declares enums in a way that is evaluated correctly by older compilers, and by newer ones that can interpret the underlying type information.

Use the NS_ENUM macro to define enumerations , a set of values that are mutually exclusive:

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

The NS_ENUM macro helps define both the name and type of the enumeration, in this case named UITableViewCellStyle of type NSInteger . The type for enumerations should be NSInteger .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM