How do I define and use an ENUM in Objective-C?

I declared an enum in my implementation file as shown below, and declared a variable of that type in my interface as PlayerState thePlayerState; and used the variable in my methods. But I am getting errors stating that it is undeclared. How do I correctly declare and use a variable of type PlayerState in my methods?:

In the .m file

@implementation View1Controller

    typedef enum playerStateTypes
        {
            PLAYER_OFF,
            PLAYER_PLAYING,
            PLAYER_PAUSED
        } PlayerState;

in the .h file:

@interface View1Controller : UIViewController {

    PlayerState thePlayerState;

in some method in .m file:

-(void)doSomethin{

thePlayerState = PLAYER_OFF;

}

Solution 1:

Apple provides a macro to help provide better code compatibility, including Swift. Using the macro looks like this.

typedef NS_ENUM(NSInteger, PlayerStateType) {
  PlayerStateOff,
  PlayerStatePlaying,
  PlayerStatePaused
};

Documented here

Solution 2:

Your typedef needs to be in the header file (or some other file that's #imported into your header), because otherwise the compiler won't know what size to make the PlayerState ivar. Other than that, it looks ok to me.

Solution 3:

In the .h:

typedef enum {
    PlayerStateOff,
    PlayerStatePlaying,
    PlayerStatePaused
} PlayerState;

Solution 4:

With current projects you may want to use the NS_ENUM() or NS_OPTIONS() macros.

typedef NS_ENUM(NSUInteger, PlayerState) {
        PLAYER_OFF,
        PLAYER_PLAYING,
        PLAYER_PAUSED
    };