Ashish Agarwal
Ashish Agarwal

Reputation: 14925

Using enums in Objective C

I have declared an enum in a .h file.

In the Event.h file

typedef enum EventType {
    MovementStart = 100019,
    MovementStop = 100020,
    HeartBeat = 100021
} EventType;

I have imported Event.h into my ViewController and am trying to use it as:

EventType eventType;
NSArray *eventTypes = [NSArray arrayWithObjects:eventType.MovementStart, nil];

This is giving me an error: Member reference base type 'EventType' (aka 'enum EventType') is not a structure or union.

How do I fix this ?

Upvotes: 1

Views: 691

Answers (2)

DanielG
DanielG

Reputation: 2377

Gavin's answer is correct but I'd like to suggest NSValue as a more general solution for any time you're trying to store non-object types such as an enum or struct in an array or dictionary: NSValue.

NSValue's purpose in life is to wrap any non-object type in a container object which can very helpful.

For example:

[NSValue value:eventType withObjCType:@encode(EventType)]

Again, not a big difference for very simple enums but in general a very useful technique to know.

Upvotes: 1

Gavin
Gavin

Reputation: 8200

First off, to reference that enum value, you wouldn't type eventType.MovementStart, you should just type MovementStart.

Second, your EventType enum values are just integers, but you can only store objects in an NSArray, so this wouldn't work anyway. You could store it by replacing eventType.MovementStart with [NSNumber numberWithInteger:MovementStart], or less verbose, @(MovementStart).

Upvotes: 5

Related Questions