Reputation: 2239
Am new to Objetive-C and today i encountered NS_ENUM marco which can be used like:
typedef NS_ENUM(Type, MyType) {
Foo,
Bar
};
The usage is a little bit weird what why typedof
must be used here, so i checked the source code of NS_ENUM:
#if (__cplusplus && __cplusplus >= 201103L &&
(__has_extension(cxx_strong_enums) ||
__has_feature(objc_fixed_enum))
) ||
(!__cplusplus && __has_feature(objc_fixed_enum))
#define NS_ENUM(_type, _name)
enum _name : _type _name; enum _name : _type
#if (__cplusplus)
#define NS_OPTIONS(_type, _name)
_type _name; enum : _type
#else
#define NS_OPTIONS(_type, _name)
enum _name : _type _name; enum _name : _type
#endif
#else
#define NS_ENUM(_type, _name) _type _name; enum
#define NS_OPTIONS(_type, _name) _type _name; enum
#endif
The way NS_ENUM is being defined makes me more confused, because i don't understand the syntax here, could anyone explain the definition from the syntactic perspective in details? Thanks.
Upvotes: 3
Views: 292
Reputation: 8170
It's a simple string substitution mechanism. This
#define NS_ENUM(_type, _name)
enum _name : _type _name; enum _name : _type
means that this
typedef NS_ENUM(int, myEnumType)
will be replaced by this
enum myEnumType : int myEnumType;
enum myEnumType : int
From this source you can see that the enum syntax is:
enum [tag] [: type] {enum-list} [declarator]; // for definition of enumerated type
enum tag declarator; // for declaration of variable of type tag
Upvotes: 4
Reputation: 112857
See: NS_ENUM & NS_OPTIONS for complete information and usage.
From NSHipster: "Introduced in Foundation with iOS 6 / Mac OS X 10.8, the NS_ENUM and NS_OPTIONS macros are the new, preferred way to declare enum types."
Upvotes: 2