Define your own constant types in Objective-C

By June 24, 2015iOS, Mobile

We are faced with the requirement of using enums frequently within our code but Objective-C Enums only allow for integer values, which don’t always fulfil our requirement. For example, if we need to store the state of a process as a string to later be sent on to a service.

Possible states:

Waiting

Running

Paused

Finished

 

If this were completed using enums, we would have something like this:

typedef enum {

Waiting,

Running,

Paused,

Finished

} ProcessState;

 

Imagine now trying to set a string value for your process property based on the enum. The result would be something like the following:

switch(state){

case Waiting:

<object>.processState = @”Waiting”;

break;

case Running:

<object>.processState = @”Running”;

break;

}

 

A more elegant solution would be to set these values directly, it’s more readable and plays nicely with auto complete. For that you need to do the following:

In your .h file:

typedef NSString ProcessState;

FOUNDATION_EXPORT ProcessState *const Waiting;

FOUNDATION_EXPORT ProcessState *const Running;

FOUNDATION_EXPORT ProcessState *const Paused;

FOUNDATION_EXPORT ProcessState *const Finished;

 

In your .m file:

ProcessState *const Waiting = @”Waiting”;

ProcessState *const Running = @”Running”;

ProcessState *const Paused = @”Paused”;

ProcessState *const Finished = @”Finished”;

 

Now just set values with:

<object>.processstate = Waiting;

 

Prefixes can enhance it further to work even better with code completion. So we can change the constant declarations to have a prefix before:

typedef NSString MPProcessState;

FOUNDATION_EXPORT MPProcessState *const Waiting;

FOUNDATION_EXPORT MPProcessState *const Running;

FOUNDATION_EXPORT MPProcessState *const Paused;

FOUNDATION_EXPORT MPProcessState *const Finished;

MPProcessState *const Waiting = @”Waiting”;

MPProcessState *const Running = @”Running”;

MPProcessState *const Paused = @”Paused”;

MPProcessState *const Finished = @”Finished”;

 

Now when we’re setting our process state property, we’re presented with a nicely human readable solution. That’s it!

Leave a Reply