37

Is it possible to get the total number of items defined by an enum at runtime?

While it's pretty much the same question as this one, that question relates to C#, and as far as I can tell, the method provided there won't work in Objective-C.

Community
  • 1
  • 1
Josh Buhler
  • 26,878
  • 9
  • 29
  • 45

2 Answers2

70

An enum is a plain-old-C type, therefore it provides no dynamic runtime information.

One alternative is to use the last element of an enum to indicate the count:

typedef enum {
    Red,
    Green,
    Blue,
    numColors
} Color;
Darren
  • 25,520
  • 5
  • 61
  • 71
0

Using preprocessors you can achieve this without the annoying 'hack' of adding an additional value to your enum

#define __YourEnums \
YourEnum_one, \
YourEnum_two, \
YourEnum_three, \
YourEnum_four, \
YourEnum_five, \
YourEnum_six,

typedef enum : NSInteger {
__YourEnums
}YourEnum;

#define YourEnum_count ({ \
NSInteger __YourEnumsArray[] = {__YourEnums}; \
sizeof(__YourEnumsArray)/sizeof(__YourEnumsArray[0]); \
})
Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195