Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use enumerated datatypes in Objective-C?

I'm working on several iOS projects where I think enumerated datatypes would be helpful to me. For example, I have a game where the player can walk in several directions. I could just define four constants with string values as kDirectionUp, kDirectionDown, etc.

I think an enumerated type would be better here. Is that correct? If so, how do I define an enum here so that I can later compare values? (As in, if(someValue == kDirectionUp){})

like image 450
Moshe Avatar asked Jun 03 '11 23:06

Moshe


People also ask

How do you declare an enum in Objective C?

Enums are defined by the following the syntax above. typedef NS_ENUM(NSUInteger, MyEnum) { MyEnumValueA, MyEnumValueB, MyEnumValueC, }; You also can set your own raw-values to the enumeration types. typedef NS_ENUM(NSUInteger, MyEnum) { MyEnumValueA = 0, MyEnumValueB = 5, MyEnumValueC = 10, };

How do you declare enumerated data types?

In this situation, one can declare the enumerated type in which only male and female values are assigned. It can be declared during declaring enumerated types, just add the name of the variable before the semicolon. or, Beside this, we can create enumerated type variables as same as the normal variables.

What is the use of enumeration data type in C?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.

What is enum base type in Objective C?

A typedef in Objective-C is exactly the same as a typedef in C. And an enum in Objective-C is exactly the same as an enum in C. This declares an enum with three constants kCircle = 0, kRectangle = 1 and kOblateSpheroid = 2, and gives the enum type the name ShapeType.


1 Answers

That sounds like the right thing to do.

It's really simple to create enums in Objective-C using C-style type definitions. For example, in one of my header files, I have the following type definition:

typedef enum {
  CFPosterViewTypePoster = 0,
  CFPosterViewTypeStart, // 1
  CFPosterViewTypeEnd,   // 2
  ....                   // 3
} CFPosterViewType;   

You define an object of CFPosterViewType and set it to one of the values:

CFPosterViewType posterType = CFPosterViewTypeStart;

When comparing CFPosterViewType values, it's as simple as doing the following:

if (posterType == CFPosterViewTypePoster) {
    // do something
}

Note that the commented out numbers in the enum above are implicit values. If you want to do something differently, say, define a bitmask, or anything else where you need the values to be different than the default, you'll need to explicitly define them.

like image 126
csano Avatar answered Oct 23 '22 12:10

csano