Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a class property as an enum type

I want to declare a custom enum such as:

enum menuItemType
{
    LinkInternal = 0,
    LinkExternal = 1,
    Image = 2,
    Movie = 3,
    MapQuery = 4
}

As a type for my object:

@interface MenuItem : NSObject {    
    NSMutableString *menuId;
    NSMutableString *title;
    enum menuItemType *menuType;
    NSMutableArray *subMenuItems;
}

But am unsure where I need to put the enum definition - if I put it before the @interface its syntactically incorrect

like image 833
Anthony Main Avatar asked Jan 22 '10 09:01

Anthony Main


People also ask

How do you declare an enum?

An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.

How do you define an enum class?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

How do you add an enum to a model class?

In your models package within coding-events , create a new class called EventType . Before you finish entering the name of your file, select the Enum option from the list of types.

How do you declare an enum in Python?

Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over. An enum has the following characteristics.


1 Answers

Just updating this in case someone stumbles upon this in our future times.

Since iOS 6 / Mac OS X 10.8, the new NS_ENUM and NS_OPTIONS macros are the preferred way to declare enum types.

In that case, it would look like:

typedef NS_ENUM(NSInteger, MenuItemType) {
    LinkInternal = 0,
    LinkExternal = 1,
    Image = 2,
    Movie = 3,
    MapQuery = 4
};

@interface MenuItem : NSObject {    
    NSMutableString *menuId;
    NSMutableString *title;
    MenuItemType menuType;
    NSMutableArray *subMenuItems;
}

A good read on the subject: http://nshipster.com/ns_enum-ns_options/

You might also want to conform to Apple's conventions for enum naming and go for something like:

typedef NS_ENUM(NSInteger, MenuItemType) {
    MenuItemTypeLinkInternal = 0,
    MenuItemTypeLinkExternal = 1,
    MenuItemTypeImage = 2,
    MenuItemTypeMovie = 3,
    MenuItemTypeMapQuery = 4
};

Hope this will help.

like image 109
Zedenem Avatar answered Sep 30 '22 22:09

Zedenem